shep-daemon 0.25.2

The supervision engine behind shep: process spawning, restart policy, the log plane, watch and cron restarts, and the RPC server
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
//! Whether this host can give every sheep its own cgroup
//!
//! [`detect`] runs once at boot. On cgroup v2 with a subtree the shepherd may
//! write, it moves itself into a `shepherd` leaf and enables the controllers a
//! sheep's limits need: the [`Cgroups::Available`] base. Else it names a [`Reason`].
//!
//! Under an available base each sheep gets `<base>/sheep-<id>-<instance>`,
//! which [`join_on_exec`] creates and the child joins before its exec, with
//! `memory.max` ([`write_memory_max`]), `cpu.max` ([`write_cpu_max`]) and
//! `pids.max` ([`write_pids_max`]) set first and [`oom_kills`] read at the exit. [`remove_stale`] drops it.

use core::fmt;
use std::ffi::OsStr;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};

use shep_core::config::CpuCores;

use crate::runner::{RunnerError, SpawnSpec};

/// The cgroup v2 mount point every unified hierarchy is read from.
const MOUNT: &str = "/sys/fs/cgroup";

/// The leaf the shepherd lives in, since v2 refuses controllers on a cgroup
/// that holds processes.
const LEAF: &str = "shepherd";

const CPU_PERIOD_US: u64 = CpuCores::PERIOD_US;

/// Written to `cgroup.subtree_control`: the controllers a sheep's limits use.
const CONTROLLERS: &str = "+memory +cpu +pids";

/// What a sheep's cgroup is capped to before its child joins: `None` leaves
/// that limit off.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Limits {
    /// Bytes for `memory.max`.
    pub memory_max: Option<u64>,
    /// Microseconds per period for `cpu.max`.
    pub cpu_quota: Option<u64>,
    /// Processes for `pids.max`.
    pub pids_max: Option<u32>,
}

impl From<&SpawnSpec> for Limits {
    fn from(spec: &SpawnSpec) -> Self {
        Self {
            memory_max: spec.memory_max,
            cpu_quota: spec.cpu_quota,
            pids_max: spec.pids_max,
        }
    }
}

/// What [`detect`] found.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Cgroups {
    /// The shepherd sits in `<base>/shepherd` and `base` can hold one child
    /// cgroup per sheep, with `memory`, `cpu` and `pids` enabled.
    Available { base: PathBuf },
    /// No sheep gets a cgroup, for this reason.
    Unavailable(Reason),
}

/// Why a host cannot give a sheep its own cgroup.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Reason {
    /// `/proc/self/cgroup` holds a v1 line, no `0::` line, or the mount at
    /// `/sys/fs/cgroup` is not cgroup2.
    NotV2,
    /// The shepherd's own cgroup refused a write: it is not delegated to this
    /// user.
    NotDelegated,
    /// The shepherd's cgroup holds a process other than the shepherd, such as
    /// the CLI that started it, so v2 refuses controllers on it.
    Busy,
    /// A read or write failed for a reason other than permission, such as a
    /// controller the parent does not offer.
    Setup(io::ErrorKind),
}

impl fmt::Display for Reason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NotV2 => f.write_str("this host is not on cgroup v2 alone"),
            Self::NotDelegated => f.write_str("the shepherd's cgroup is not delegated to it"),
            Self::Busy => f.write_str("the shepherd's cgroup holds another process"),
            Self::Setup(kind) => write!(f, "setting up the shepherd's cgroup failed: {kind}"),
        }
    }
}

impl fmt::Display for Cgroups {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Available { base } => {
                write!(f, "cgroup v2 available under {}", base.display())
            }
            Self::Unavailable(reason) => write!(f, "cgroups unavailable: {reason}"),
        }
    }
}

/// Finds the cgroup v2 subtree this shepherd may write, and moves the
/// shepherd into its leaf.
///
/// Idempotent: a shepherd already in `<base>/shepherd`, as after
/// `shep daemon reload`'s `execve`, finds the same base.
pub(crate) fn detect() -> Cgroups {
    detect_at(
        Path::new("/proc/self/cgroup"),
        Path::new(MOUNT),
        std::process::id(),
    )
}

/// [`detect`] against a `/proc/self/cgroup` file and a cgroup2 `mount`, which
/// a test points at a temp directory.
fn detect_at(proc_cgroup: &Path, mount: &Path, pid: u32) -> Cgroups {
    match try_detect(proc_cgroup, mount, pid) {
        Ok(found) => found,
        Err(reason) => Cgroups::Unavailable(reason),
    }
}

fn try_detect(proc_cgroup: &Path, mount: &Path, pid: u32) -> Result<Cgroups, Reason> {
    let text = fs::read_to_string(proc_cgroup).map_err(|err| Reason::Setup(err.kind()))?;
    let own = unified_path(&text).ok_or(Reason::NotV2)?;
    if !mount.join("cgroup.controllers").is_file() {
        return Err(Reason::NotV2);
    }

    let own_dir = mount.join(own.trim_start_matches('/'));
    let base = if own_dir.file_name().is_some_and(|name| name == LEAF) {
        own_dir.parent().unwrap_or(mount).to_path_buf()
    } else {
        if holds_another_process(&own_dir, pid) {
            return Err(Reason::Busy);
        }
        move_into_leaf(&own_dir.join(LEAF), pid)?;
        own_dir
    };
    fs::write(base.join("cgroup.subtree_control"), CONTROLLERS).map_err(|err| {
        match err.kind() {
            io::ErrorKind::ResourceBusy => Reason::Busy,
            _ => classify(&err),
        }
    })?;
    Ok(Cgroups::Available { base })
}

/// Whether `dir`'s `cgroup.procs` lists a pid other than `pid`. An unreadable
/// file is none: the write that follows reports the real error.
fn holds_another_process(dir: &Path, pid: u32) -> bool {
    fs::read_to_string(dir.join("cgroup.procs")).is_ok_and(|procs| {
        procs
            .split_whitespace()
            .any(|listed| listed.parse::<u32>().is_ok_and(|listed| listed != pid))
    })
}

/// Creates `leaf` and writes `pid` into it, removing a leaf this call made
/// if the write fails.
fn move_into_leaf(leaf: &Path, pid: u32) -> Result<(), Reason> {
    let created = match fs::create_dir(leaf) {
        Ok(()) => true,
        Err(err) if err.kind() == io::ErrorKind::AlreadyExists => false,
        Err(err) => return Err(classify(&err)),
    };
    fs::write(leaf.join("cgroup.procs"), pid.to_string()).map_err(|err| {
        if created {
            let _ = fs::remove_dir(leaf);
        }
        classify(&err)
    })
}

/// The path on the only line of a v2-only `/proc/self/cgroup`: a v1 line
/// anywhere, as on a hybrid host, is none.
fn unified_path(text: &str) -> Option<&str> {
    let mut lines = text.lines().filter(|line| !line.is_empty());
    let path = lines.next()?.strip_prefix("0::")?;
    lines.next().is_none().then_some(path)
}

fn classify(err: &io::Error) -> Reason {
    match err.kind() {
        io::ErrorKind::PermissionDenied | io::ErrorKind::ReadOnlyFilesystem => Reason::NotDelegated,
        kind => Reason::Setup(kind),
    }
}

/// Where the sheep with `id` and `instance` lives under `base`. The name is a
/// function of both, so a successor after `shep daemon reload` finds it again.
pub(crate) fn sheep_dir(base: &Path, id: u32, instance: u32) -> PathBuf {
    base.join(format!("sheep-{id}-{instance}"))
}

/// Whether `name` is one [`sheep_dir`] makes.
fn is_sheep_dir(name: &OsStr) -> bool {
    name.to_str()
        .and_then(|name| name.strip_prefix("sheep-"))
        .and_then(|rest| rest.split_once('-'))
        .is_some_and(|(id, instance)| id.parse::<u32>().is_ok() && instance.parse::<u32>().is_ok())
}

/// Creates the cgroup at `dir` and makes `command`'s child join it before it
/// execs. A kill of any process in it takes the whole group, through
/// `memory.oom.group`. `limits` are written first; a key left `None` lifts the
/// limit an earlier sheep left in a reused `dir`.
///
/// `dir` may already exist, as after a restart that reuses its name, but not
/// with a process in it: a sheep that outlived a crashed shepherd keeps its
/// cgroup, and a new sheep with the same id must not share it.
///
/// # Errors
/// What creating the directory, writing `memory.oom.group` or a limit, or
/// opening `cgroup.procs` reported, or [`io::ErrorKind::ResourceBusy`] when `dir`
/// already holds a process. A directory this call made is removed again.
pub(crate) fn join_on_exec(
    command: &mut std::process::Command,
    dir: &Path,
    limits: Limits,
) -> io::Result<()> {
    let created = match fs::create_dir(dir) {
        Ok(()) => true,
        Err(err) if err.kind() == io::ErrorKind::AlreadyExists => false,
        Err(err) => return Err(err),
    };
    let procs = if is_occupied(dir) {
        Err(io::Error::from(io::ErrorKind::ResourceBusy))
    } else {
        fs::write(dir.join("memory.oom.group"), "1")
            .and_then(|()| {
                write_unless_fresh(created, limits.memory_max, |l| write_memory_max(dir, l))
            })
            .and_then(|()| write_unless_fresh(created, limits.cpu_quota, |l| write_cpu_max(dir, l)))
            .and_then(|()| write_unless_fresh(created, limits.pids_max, |l| write_pids_max(dir, l)))
            .and_then(|()| {
                fs::OpenOptions::new()
                    .write(true)
                    .open(dir.join("cgroup.procs"))
            })
    }
    .inspect_err(|_| {
        if created {
            let _ = fs::remove_dir(dir);
        }
    })?;
    crate::sys::join_cgroup_on_exec(command, procs);
    Ok(())
}

/// Writes one of [`Limits`] through `write`. A limit of `None` is written, as
/// the lifted value, only into a cgroup that already existed: it may carry the
/// limit of the sheep that held it before, and a directory this call made
/// holds the kernel's defaults already.
fn write_unless_fresh<T>(
    created: bool,
    limit: Option<T>,
    write: impl FnOnce(Option<T>) -> io::Result<()>,
) -> io::Result<()> {
    if limit.is_none() && created {
        Ok(())
    } else {
        write(limit)
    }
}

/// Writes `limit` bytes to `dir`'s `memory.max`, or `max` (no cap) for `None`.
///
/// `memory.swap.max` follows, best effort: `0` under a cap, so a sheep over it
/// is killed rather than pushed to swap, and `max` again without one. A host
/// with no swap accounting has no such file, and the cap holds without it.
///
/// # Errors
/// What the `memory.max` write reported, such as a cgroup the `memory`
/// controller is not enabled for.
pub(crate) fn write_memory_max(dir: &Path, limit: Option<u64>) -> io::Result<()> {
    let (max, swap) = match limit {
        Some(bytes) => (bytes.to_string(), "0"),
        None => ("max".to_string(), "max"),
    };
    fs::write(dir.join("memory.max"), max)?;
    let _ = fs::write(dir.join("memory.swap.max"), swap);
    Ok(())
}

/// The microseconds of CPU time per [`CPU_PERIOD_US`] that `cores` allows,
/// rounded to the nearest microsecond.
pub(crate) fn cpu_quota(cores: CpuCores) -> u64 {
    cores.quota_us()
}

/// Writes `<quota> <period>` to `dir`'s `cpu.max`, or `max <period>` (no cap)
/// for `None`. The tree is throttled, never killed.
///
/// # Errors
/// What the `cpu.max` write reported, such as a cgroup the `cpu` controller
/// is not enabled for, or a quota under the kernel's one-millisecond minimum.
pub(crate) fn write_cpu_max(dir: &Path, quota: Option<u64>) -> io::Result<()> {
    let quota = quota.map_or_else(|| "max".to_string(), |micros| micros.to_string());
    fs::write(dir.join("cpu.max"), format!("{quota} {CPU_PERIOD_US}"))
}

/// Writes `limit` to `dir`'s `pids.max`, or `max` (no limit) for `None`. A fork
/// past it fails with `EAGAIN` inside the sheep; nothing is killed.
///
/// # Errors
/// What the `pids.max` write reported, such as a cgroup the `pids` controller
/// is not enabled for, or a limit above the kernel's own ceiling.
pub(crate) fn write_pids_max(dir: &Path, limit: Option<u32>) -> io::Result<()> {
    let limit = limit.map_or_else(|| "max".to_string(), |tasks| tasks.to_string());
    fs::write(dir.join("pids.max"), limit)
}

/// How many of the cgroup's own processes the kernel's OOM killer has killed,
/// off `memory.events.local`. `0` when the file is absent or unreadable, as for
/// a cgroup not made yet.
///
/// Local, not `memory.events`: the latter also counts kills anywhere below
/// `dir`, so an ancestor's OOM could pass for this sheep's own. The counter is
/// cumulative, so a caller compares two readings.
pub(crate) fn oom_kills(dir: &Path) -> u64 {
    fs::read_to_string(dir.join("memory.events.local")).map_or(0, |text| parse_oom_kill(&text))
}

/// The `oom_kill` line's value in a `memory.events` listing, `0` without one.
fn parse_oom_kill(text: &str) -> u64 {
    text.lines()
        .filter_map(|line| line.strip_prefix("oom_kill "))
        .find_map(|value| value.trim().parse().ok())
        .unwrap_or(0)
}

/// Whether `dir`'s `cgroup.procs` lists a process. A listing is `<pid>\n` per
/// process, so its first byte is a digit: one byte tells, and an endless file
/// such as `/dev/full` is neither read to its end nor taken for a listing.
fn is_occupied(dir: &Path) -> bool {
    let mut first = [0u8; 1];
    fs::File::open(dir.join("cgroup.procs"))
        .and_then(|mut procs| io::Read::read(&mut procs, &mut first))
        .is_ok_and(|read| read == 1 && first[0].is_ascii_digit())
}

/// The error for a spawn that failed after [`join_on_exec`], which may be the
/// join itself: the child reports both the same way. Drops the cgroup.
pub(crate) fn spawn_failed(name: &str, dir: &Path, error: &io::Error) -> RunnerError {
    let _ = remove_if_empty(dir);
    RunnerError::SpawnFailed(format!(
        "{name} could not start in cgroup {}: {error}",
        dir.display()
    ))
}

/// Removes `dir` unless a process is still in it, which the kernel would
/// refuse anyway. A directory already gone is removed.
///
/// # Errors
/// What `cgroup.procs` or the removal reported, other than the directory
/// being absent.
pub(crate) fn remove_if_empty(dir: &Path) -> io::Result<()> {
    if is_occupied(dir) {
        return Ok(());
    }
    match fs::remove_dir(dir) {
        Err(err) if err.kind() != io::ErrorKind::NotFound => Err(err),
        _ => Ok(()),
    }
}

/// Drops the cgroup of a spawn that failed before the child existed, which no
/// exit will ever clean up. `None` is a spawn with no cgroup.
pub(crate) fn release(dir: Option<&Path>) {
    if let Some(dir) = dir {
        let _ = remove_if_empty(dir);
    }
}

/// Removes every empty `sheep-<id>-<instance>` cgroup under `base`, which a
/// shepherd that crashed left behind. One with a process in it stays, so a
/// sheep that outlived the crash or crossed a reload keeps its cgroup.
pub(crate) fn remove_stale(base: &Path) {
    let Ok(entries) = fs::read_dir(base) else {
        return;
    };
    for entry in entries.flatten() {
        if !is_sheep_dir(&entry.file_name()) {
            continue;
        }
        if let Err(error) = remove_if_empty(&entry.path()) {
            tracing::warn!(%error, cgroup = %entry.path().display(), "stale sheep cgroup not removed");
        }
    }
}

#[cfg(test)]
mod cpu_tests;
#[cfg(test)]
mod task_tests;
#[cfg(test)]
mod tests;