rlmctl-core 0.2.3

cgroup v2 limit management and the rlm-guard engine for rlmctl
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
//! Persistent application rules: keep matching processes in a shared per-app
//! cgroup with the rule's limits, continuously reconciled by `rlm-guard`.
//!
//! The decision logic ([`plan`]) is pure and takes an injected snapshot of the
//! currently-running processes plus the set of PIDs already placed, so it is
//! unit-testable without root. [`RulesEnforcer::reconcile`] wires that decision
//! to the caller's process snapshot and a [`CgroupManager`].

use std::collections::{HashMap, HashSet};
use std::os::unix::fs::MetadataExt;

use crate::guard::cgfs;
use crate::process::ProcessInfo;
use crate::CgroupManager;
use common::{AppRule, Config, Limit};

/// A rule with its limits parsed once up front.
pub struct CompiledRule {
    pub name: String,
    pub match_exe: Vec<String>,
    pub limit: Limit,
    /// Shared cgroup name for this rule (`app-<name>`).
    pub cgroup: String,
}

/// One reconcile decision for a single rule.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RuleAction {
    /// Ensure the shared cgroup exists with the rule's limits set.
    EnsureCgroup { rule: String },
    /// Add a matching process to the rule's shared cgroup.
    AddPid { rule: String, pid: u32 },
    /// No matching processes remain — tear down the (now empty) cgroup.
    TeardownEmpty { rule: String },
}

/// Sanitize a rule name into the `app-<name>` cgroup form, matching the CLI's
/// existing scheme (`app-{name with '/' and ' ' replaced by '_'}`).
pub fn cgroup_name_for(rule_name: &str) -> String {
    format!("app-{}", rule_name.replace(['/', ' '], "_"))
}

impl CompiledRule {
    fn compile(name: &str, rule: &AppRule) -> Option<Self> {
        match rule.to_limit() {
            Ok(limit) => Some(CompiledRule {
                name: name.to_string(),
                match_exe: rule.match_exe.clone(),
                limit,
                cgroup: cgroup_name_for(name),
            }),
            Err(e) => {
                tracing::warn!(rule = name, error = %e, "skipping rule with invalid limits");
                None
            }
        }
    }

    fn matches(&self, proc: &ProcessInfo) -> bool {
        self.match_exe.iter().any(|want| {
            proc.name == *want
                || proc
                    .executable
                    .as_ref()
                    .and_then(|exe| exe.file_name())
                    .and_then(|n| n.to_str())
                    .map(|n| n == want)
                    .unwrap_or(false)
        })
    }
}

/// Pure planner: decide the actions for one rule given the current process
/// snapshot, the PIDs already in this rule's cgroup, and whether this rule's
/// cgroup currently has any process in it.
///
/// - matches present, some not placed              -> EnsureCgroup + AddPid(each new)
/// - matches present, all already placed            -> EnsureCgroup only (idempotent)
/// - no matches, cgroup occupied                    -> nothing (don't evict)
/// - no matches, cgroup empty-but-present            -> TeardownEmpty
/// - no matches, no cgroup                           -> nothing
///
/// The freeze guard no longer migrates processes into a separate `guard-<pid>`
/// cgroup — it acts in place on whatever cgroup a process already lives in
/// (see `guard/effector.rs`), and rule cgroups are first-class guard targets.
/// So there IS something left to contend over: `held` is `true` when the
/// guard currently holds a freeze or cap intervention on this rule's cgroup
/// (see `RulesEnforcer::reconcile`), in which case this rule's actions are
/// skipped outright for the tick — rewriting `memory.high`/adding PIDs out
/// from under an active intervention would silently no-op the guard's action
/// while leaving `PolicyEngine` believing it still holds one.
pub fn plan(
    rule: &CompiledRule,
    procs: &[ProcessInfo],
    already_placed: &[u32],
    cgroup_exists: bool,
    held: bool,
) -> Vec<RuleAction> {
    if held {
        return Vec::new();
    }

    let matches: Vec<&ProcessInfo> = procs.iter().filter(|p| rule.matches(p)).collect();

    if matches.is_empty() {
        // Only tear down a cgroup that exists AND is empty. A populated
        // `app-<exe>` (e.g. created by a manual one-off `--application` limit
        // that shares the name) must never be evicted from under its owner.
        return if cgroup_exists && already_placed.is_empty() {
            vec![RuleAction::TeardownEmpty {
                rule: rule.name.clone(),
            }]
        } else {
            Vec::new()
        };
    }

    let mut actions = vec![RuleAction::EnsureCgroup {
        rule: rule.name.clone(),
    }];
    for p in matches {
        if !already_placed.contains(&p.pid) {
            actions.push(RuleAction::AddPid {
                rule: rule.name.clone(),
                pid: p.pid,
            });
        }
    }
    actions
}

/// Whether a rule cgroup's limits must be (re)written. `recorded_inode` is
/// the cgroup directory's inode when the limits were last written,
/// `current_inode` its inode now (`None`: the cgroup does not exist). Limits
/// are rewritten only when the cgroup is new or was recreated: writing
/// `memory.high` below current usage makes the writer reclaim synchronously,
/// so rewriting unchanged limits every tick costs the daemon real work under
/// exactly the pressure it exists to handle.
pub fn needs_ensure(recorded_inode: Option<u64>, current_inode: Option<u64>) -> bool {
    current_inode.is_none() || recorded_inode != current_inode
}

/// Enforces persistent application rules against real cgroups.
pub struct RulesEnforcer {
    rules: Vec<CompiledRule>,
    /// Rule cgroup name to the directory inode at the last limit write.
    ensured: HashMap<String, u64>,
}

impl RulesEnforcer {
    /// Compile the rules from config. Rules with unparseable limits are skipped
    /// (logged once) rather than failing the whole enforcer.
    pub fn new(cfg: &Config) -> Self {
        let rules = cfg
            .rules
            .iter()
            .filter_map(|(name, rule)| CompiledRule::compile(name, rule))
            .collect();
        Self {
            rules,
            ensured: HashMap::new(),
        }
    }

    pub fn rule_count(&self) -> usize {
        self.rules.len()
    }

    /// Reconcile every rule once against `procs`, a snapshot of the user's
    /// processes (the daemon shares one `/proc` scan per tick between the
    /// guard and this). Best-effort: a failure on one rule or PID is logged
    /// and never aborts the others. Returns the actions that were applied
    /// (useful for logging/tests). An `EnsureCgroup` whose cgroup already
    /// carries the limits (same inode as at the last write, see
    /// [`needs_ensure`]) writes nothing and is not reported.
    ///
    /// `held_cgroups` is `PolicyEngine::intervened_cgroups()`: the cgroups
    /// the freeze guard currently holds a freeze *or* cap intervention on
    /// (D1 fix). A rule whose cgroup is in that set is skipped entirely for
    /// the tick: `RulesEnforcer` and the guard both write to the same rule
    /// cgroup (act-in-place makes rule cgroups first-class guard targets),
    /// and rewriting `memory.high` on a cgroup the guard just capped would
    /// silently revert the cap while leaving `PolicyEngine` believing it
    /// still holds one.
    pub fn reconcile(
        &mut self,
        mgr: &CgroupManager,
        procs: &[ProcessInfo],
        held_cgroups: &[String],
    ) -> Vec<RuleAction> {
        // rlm's own base cgroup path, relative to /sys/fs/cgroup (same
        // convention cgfs uses), for building each rule's held/frozen-check
        // path below. `None` only if base_path is somehow outside
        // /sys/fs/cgroup (broken invariant) — both checks are then skipped
        // rather than guessed at.
        let rlm_rel = crate::guard::sampler::strip_cgroup_root(mgr.base_path());
        let held: HashSet<&str> = held_cgroups.iter().map(String::as_str).collect();

        let mut applied = Vec::new();
        for rule in &self.rules {
            let mut blocked = false;
            if let Some(rel) = &rlm_rel {
                let cg_path = format!("{rel}/{}", rule.cgroup);

                // First guard: the engine's own bookkeeping says it currently
                // holds a freeze or cap on this cgroup — skip so we don't
                // fight/revert it (D1).
                if held.contains(cg_path.as_str()) {
                    blocked = true;
                }

                // Second, independent guard: ask the kernel directly whether
                // the cgroup is frozen, regardless of our own bookkeeping —
                // the freeze may not even be ours (e.g. a systemd unit
                // paused for an unrelated reason) — and skip this rule's
                // actions for the tick rather than fight a paused cgroup
                // (adding a PID to a frozen cgroup silently queues it
                // frozen; tearing one down while frozen can wedge cleanup).
                // We'll reconcile normally once it thaws.
                if !blocked && cgfs::read_frozen(&cg_path) == Some(true) {
                    blocked = true;
                }
            }

            // Which matching PIDs are already in this rule's cgroup?
            let placed = mgr.pids_in_cgroup(&rule.cgroup);
            let exists = !placed.is_empty() || mgr.cgroup_exists(&rule.cgroup);

            for action in plan(rule, procs, &placed, exists, blocked) {
                match apply(mgr, rule, &action, &mut self.ensured) {
                    Ok(true) => applied.push(action),
                    Ok(false) => {}
                    Err(e) => tracing::warn!(?action, error = %e, "rules: action failed"),
                }
            }
        }
        applied
    }
}

/// Inode of a rule cgroup's directory, or `None` if it does not exist.
fn cgroup_inode(mgr: &CgroupManager, cgroup: &str) -> Option<u64> {
    std::fs::metadata(mgr.base_path().join(cgroup))
        .ok()
        .map(|m| m.ino())
}

/// Apply one action. `Ok(false)` means nothing needed doing.
fn apply(
    mgr: &CgroupManager,
    rule: &CompiledRule,
    action: &RuleAction,
    ensured: &mut HashMap<String, u64>,
) -> common::Result<bool> {
    match action {
        RuleAction::EnsureCgroup { .. } => {
            let current = cgroup_inode(mgr, &rule.cgroup);
            if !needs_ensure(ensured.get(&rule.cgroup).copied(), current) {
                return Ok(false);
            }
            // prepare_cgroup creates the cgroup (idempotent) and (re)sets limits.
            let prepared = mgr.prepare_cgroup(&rule.cgroup, &rule.limit)?;
            for w in &prepared.warnings {
                tracing::warn!(cgroup = %rule.cgroup, "{w}");
            }
            match cgroup_inode(mgr, &rule.cgroup) {
                Some(ino) => ensured.insert(rule.cgroup.clone(), ino),
                None => ensured.remove(&rule.cgroup),
            };
            Ok(true)
        }
        RuleAction::AddPid { pid, .. } => {
            let path = mgr.base_path().join(&rule.cgroup);
            mgr.add_to_cgroup(&path, *pid).map(|()| true)
        }
        RuleAction::TeardownEmpty { .. } => {
            ensured.remove(&rule.cgroup);
            mgr.cleanup_cgroup(&rule.cgroup).map(|()| true)
        }
    }
}

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

    fn rule(name: &str, exes: &[&str]) -> CompiledRule {
        CompiledRule {
            name: name.to_string(),
            match_exe: exes.iter().map(|s| s.to_string()).collect(),
            limit: Limit::default(),
            cgroup: cgroup_name_for(name),
        }
    }

    fn proc(pid: u32, name: &str, exe: Option<&str>) -> ProcessInfo {
        ProcessInfo {
            pid,
            name: name.to_string(),
            executable: exe.map(PathBuf::from),
            ..Default::default()
        }
    }

    #[test]
    fn ensure_only_when_new_or_recreated() {
        assert!(needs_ensure(None, None), "missing cgroup");
        assert!(needs_ensure(None, Some(7)), "never written");
        assert!(needs_ensure(Some(7), Some(9)), "recreated with a new inode");
        assert!(needs_ensure(Some(7), None), "removed since");
        assert!(!needs_ensure(Some(7), Some(7)), "unchanged: no writes");
    }

    #[test]
    fn cgroup_name_matches_cli_scheme() {
        assert_eq!(cgroup_name_for("firefox"), "app-firefox");
        assert_eq!(cgroup_name_for("my app/x"), "app-my_app_x");
    }

    #[test]
    fn matches_by_comm_or_exe_basename() {
        let r = rule("firefox", &["firefox"]);
        assert!(r.matches(&proc(1, "firefox", None)));
        assert!(r.matches(&proc(2, "Web Content", Some("/usr/lib/firefox/firefox"))));
        assert!(!r.matches(&proc(3, "code", Some("/usr/bin/code"))));
    }

    #[test]
    fn plan_ensures_and_adds_unplaced_matches() {
        let r = rule("firefox", &["firefox"]);
        let procs = vec![proc(10, "firefox", None), proc(11, "firefox", None)];
        let actions = plan(&r, &procs, &[], false, false);
        assert_eq!(
            actions[0],
            RuleAction::EnsureCgroup {
                rule: "firefox".into()
            }
        );
        assert!(actions.contains(&RuleAction::AddPid {
            rule: "firefox".into(),
            pid: 10
        }));
        assert!(actions.contains(&RuleAction::AddPid {
            rule: "firefox".into(),
            pid: 11
        }));
    }

    #[test]
    fn plan_is_idempotent_when_all_placed() {
        let r = rule("firefox", &["firefox"]);
        let procs = vec![proc(10, "firefox", None)];
        let actions = plan(&r, &procs, &[10], true, false);
        // Ensure only; no AddPid for the already-placed pid.
        assert_eq!(
            actions,
            vec![RuleAction::EnsureCgroup {
                rule: "firefox".into()
            }]
        );
    }

    #[test]
    fn plan_adds_only_new_pid() {
        let r = rule("firefox", &["firefox"]);
        let procs = vec![proc(10, "firefox", None), proc(12, "firefox", None)];
        let actions = plan(&r, &procs, &[10], true, false);
        assert_eq!(
            actions,
            vec![
                RuleAction::EnsureCgroup {
                    rule: "firefox".into()
                },
                RuleAction::AddPid {
                    rule: "firefox".into(),
                    pid: 12
                },
            ]
        );
    }

    #[test]
    fn plan_teardown_only_when_empty_and_present() {
        let r = rule("firefox", &["firefox"]);
        // Present + empty (no placed pids) + no matches -> teardown.
        let actions = plan(&r, &[proc(1, "code", None)], &[], true, false);
        assert_eq!(
            actions,
            vec![RuleAction::TeardownEmpty {
                rule: "firefox".into()
            }]
        );
    }

    #[test]
    fn plan_does_not_evict_occupied_cgroup_with_no_matches() {
        // No rule-matching process, but the cgroup still holds something (e.g. a
        // manual one-off `--application firefox` sharing the name). Must NOT tear
        // it down out from under its owner.
        let r = rule("firefox", &["firefox"]);
        let actions = plan(&r, &[proc(1, "code", None)], &[999], true, false);
        assert!(
            actions.is_empty(),
            "must not evict an occupied cgroup: {actions:?}"
        );
    }

    #[test]
    fn plan_noop_when_no_matches_and_no_cgroup() {
        let r = rule("firefox", &["firefox"]);
        let actions = plan(&r, &[proc(1, "code", None)], &[], false, false);
        assert!(actions.is_empty());
    }

    // ---- D1: guard-held rule cgroups --------------------------------------

    #[test]
    fn plan_produces_no_actions_when_rule_cgroup_is_guard_held() {
        // Matching processes exist and the cgroup is populated, which would
        // normally yield EnsureCgroup (+ AddPid for anything unplaced) — but
        // the guard currently holds a freeze/cap intervention on this rule's
        // cgroup, so nothing should be emitted at all.
        let r = rule("firefox", &["firefox"]);
        let procs = vec![proc(10, "firefox", None), proc(11, "firefox", None)];
        let actions = plan(&r, &procs, &[10], true, true);
        assert!(
            actions.is_empty(),
            "a guard-held rule cgroup must get no actions: {actions:?}"
        );
    }

    #[test]
    fn plan_unheld_rule_is_unaffected() {
        // Same scenario, `held = false`: normal EnsureCgroup + AddPid(new).
        let r = rule("firefox", &["firefox"]);
        let procs = vec![proc(10, "firefox", None), proc(11, "firefox", None)];
        let actions = plan(&r, &procs, &[10], true, false);
        assert!(actions.contains(&RuleAction::EnsureCgroup {
            rule: "firefox".into()
        }));
        assert!(actions.contains(&RuleAction::AddPid {
            rule: "firefox".into(),
            pid: 11
        }));
    }
}