runnerd-core 0.1.5

Config, domain logic and API types shared by runnerd and its clients
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
//! What the sizing advice means as every client shows it: what a set of jobs needs and why, how the advice reads at
//! a glance, what auto sizing does next with a profile at a given time, how much history it covers, and doctor's
//! check of it. Plain derivations of [`Sizing`]; the daemon's advice uses [`need`] for its arithmetic.

use super::{
    Advice, AutoPlan, JobSizing, MemoryBound, MemoryHold, PAGE_CACHE_ROOM, Peaks, ProfileSizing,
    Sizing, SizingChange, SizingHold, SizingRefused, Starts,
};
use crate::api::{
    Check, CheckStatus, JOBS_HEADING, LabelledFigure, Tone, Toned, cores_used, duration,
};
use crate::config::ByteSize;

/// Advice rounds memory up to a multiple of this: 256M.
pub const GRANULE: u64 = 256 << 20;

/// Seconds between two samples of a running job's container. Clients without a `Sizing` or `SampleSeries` that
/// says so, such as a job's figures in `runnerctl`, word their sampling caveat from it.
pub const SAMPLE_INTERVAL: u64 = 2;

/// What a set of jobs whose largest sampled peak is `peak` needs, with `margin` percent: the peak plus the margin, or
/// plus `PAGE_CACHE_ROOM` when that is more, rounded up to `GRANULE`. The largest, not a percentile: the cap kills a
/// job that goes over it, so a cap below a peak a job reached kills it again.
pub fn need(peak: u64, margin: u32) -> u64 {
    let room = (peak.saturating_mul(u64::from(margin)) / 100).max(PAGE_CACHE_ROOM);
    peak.saturating_add(room)
        .div_ceil(GRANULE)
        .saturating_mul(GRANULE)
        .max(GRANULE)
}

/// The caveat on a sampled peak, as every client words it: `memory peaks are sampled every 2 s; spikes shorter than
/// that do not show`.
pub fn sampled_note(interval: u64) -> String {
    format!("memory peaks are sampled every {interval} s; spikes shorter than that do not show")
}

/// What a set of jobs needs, as the advice sizes for it, from `Sizing::need`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Need {
    /// In bytes.
    pub memory: u64,
    /// How it comes from the largest peak: `its largest peak + 15%` or `its largest peak + 1G for page cache`.
    pub reason: String,
}

impl Sizing {
    /// What `profile`'s jobs need: the advice's memory, or what a bound of the config holds it away from
    /// (`ProfileSizing::hold`), or with too few jobs for advice, what it would size for.
    pub fn need(&self, profile: &ProfileSizing) -> Need {
        let peaks = &profile.peaks;
        let memory = match profile.advice {
            _ if let Some(hold) = profile.hold => hold.need,
            Advice::Keep { memory }
            | Advice::Lower { memory, .. }
            | Advice::Raise { memory, .. }
            | Advice::SliceTooSmall { memory } => memory,
            Advice::TooFew { .. } => need(peaks.memory.max, self.margin),
        };
        Need {
            memory,
            reason: self.need_reason(peaks),
        }
    }

    /// How the advice comes from `peaks`' largest: `its largest peak + 15%`, or `its largest peak + 1G for page
    /// cache` when that is more.
    pub(crate) fn need_reason(&self, peaks: &Peaks) -> String {
        if peaks.memory.max * u64::from(self.margin) / 100 >= PAGE_CACHE_ROOM {
            format!("its largest peak + {}%", self.margin)
        } else {
            format!(
                "its largest peak + {} for page cache",
                ByteSize(PAGE_CACHE_ROOM)
            )
        }
    }

    /// How the advice is made, as every client explains it: `peaks are sampled every 2 s, so a shorter spike goes
    /// unseen: advice sizes for the largest + 15%, at least 1G for page cache, rounded up to 256M, once a profile ran
    /// 10 jobs`.
    pub fn method_line(&self) -> String {
        format!(
            "peaks are sampled every {} s, so a shorter spike goes unseen: advice sizes for the largest + {}%, at \
             least {} for page cache, rounded up to {}, once a profile ran {} jobs",
            self.sample_interval,
            self.margin,
            ByteSize(PAGE_CACHE_ROOM),
            ByteSize(GRANULE),
            self.min_jobs
        )
    }

    /// `Sizing::method_line` in short parts for a heading, the sampling caveat first: `peaks sampled every 2 s`,
    /// `+15%, at least 1G, in 256M steps` and `advice after 10 jobs`.
    pub fn method_parts(&self) -> Vec<String> {
        vec![
            format!("peaks sampled every {} s", self.sample_interval),
            format!(
                "+{}%, at least {}, in {} steps",
                self.margin,
                ByteSize(PAGE_CACHE_ROOM),
                ByteSize(GRANULE)
            ),
            format!("advice after {} jobs", self.min_jobs),
        ]
    }

    /// The history it was computed from: `since` to when it was computed, however long ago that was.
    pub fn covered(&self) -> u64 {
        self.until.saturating_sub(self.since)
    }

    /// Doctor's check of it: a warning while a profile needs more memory than its cap, else the profiles whose
    /// advice changes something, or that all fit.
    pub fn doctor_check(&self) -> Check {
        let changes: Vec<_> = self
            .profiles
            .iter()
            .filter(|profile| {
                profile.advice.change().is_some()
                    || matches!(profile.advice, Advice::SliceTooSmall { .. })
            })
            .collect();
        let raise = changes
            .iter()
            .any(|profile| profile.advice.tone() == Tone::Bad);
        let detail = if changes.is_empty() {
            let too_few = self
                .profiles
                .iter()
                .any(|profile| matches!(profile.advice, Advice::TooFew { .. }));
            if too_few {
                format!(
                    "some profiles ran fewer than {} jobs; runnerctl sizing shows their peaks",
                    self.min_jobs
                )
            } else {
                format!(
                    "every profile's memory fits its jobs' largest peak + {}%, at least {} for page cache",
                    self.margin,
                    ByteSize(PAGE_CACHE_ROOM)
                )
            }
        } else {
            changes
                .iter()
                .map(|profile| format!("{}: {}", profile.name, self.advice_line(profile)))
                .collect::<Vec<_>>()
                .join("; ")
        };
        Check {
            name: "sizing".to_owned(),
            status: if raise {
                CheckStatus::Warn
            } else {
                CheckStatus::Info
            },
            detail,
            fix: (!changes.is_empty()).then(|| {
                changes
                    .iter()
                    .map(|profile| match profile.advice {
                        Advice::SliceTooSmall { .. } => match profile.held().map(|hold| hold.by) {
                            Some(MemoryBound::Ceiling { .. }) => format!(
                                "raise [host] memory_ceiling if the host can grow further, then: runnerctl \
                                 sizing apply {}",
                                profile.name
                            ),
                            Some(MemoryBound::MaxMemory | MemoryBound::MinMemory) => format!(
                                "raise max_memory in [profiles.{0}], then: runnerctl sizing apply {0}",
                                profile.name
                            ),
                            None => format!(
                                "raise MemoryMax in the slice's unit file, sudo systemctl daemon-reload, then: \
                                 runnerctl sizing apply {}",
                                profile.name
                            ),
                        },
                        _ => format!("runnerctl sizing apply {}", profile.name),
                    })
                    .collect::<Vec<_>>()
                    .join("\n")
            }),
        }
    }
}

impl Advice {
    /// What it means for the reader: more memory needed is bad, a lowering worth a look, a fitting cap good, too
    /// few jobs to tell in the background.
    pub fn tone(&self) -> Tone {
        match self {
            Advice::Raise { .. } | Advice::SliceTooSmall { .. } => Tone::Bad,
            Advice::Lower { .. } => Tone::Warn,
            Advice::Keep { .. } => Tone::Good,
            Advice::TooFew { .. } => Tone::Quiet,
        }
    }

    /// It in a word or two, for a table cell: `too few`, `keep`, `grow slice`, or the new `9G × 2`.
    pub fn word(&self) -> String {
        match *self {
            Advice::TooFew { .. } => "too few".to_owned(),
            Advice::Keep { .. } => "keep".to_owned(),
            Advice::SliceTooSmall { .. } => "grow slice".to_owned(),
            Advice::Lower { memory, slots } | Advice::Raise { memory, slots } => {
                format!("{} × {slots}", ByteSize(memory))
            }
        }
    }
}

impl ProfileSizing {
    /// What keeps its `memory` where it is although its jobs need more, `[host] memory_ceiling` or `max_memory`: no
    /// raise is possible until that grows. `None` while a raise is possible or the slice is what has to grow.
    pub fn held(&self) -> Option<MemoryHold> {
        self.hold.filter(|hold| {
            matches!(self.advice, Advice::SliceTooSmall { .. })
                && hold.by != MemoryBound::MinMemory
                && self.memory >= hold.bound
        })
    }

    /// Its figures, in the order they show: its jobs, how busy its slots were, its jobs' p50 and p95 wait, its warm
    /// starts out of all, and its jobs' CPU p99 out of its `cpus`; `–` where no job took one.
    pub fn figures(&self) -> Vec<LabelledFigure> {
        let starts = &self.starts;
        let warm = if starts.warm > 0 {
            LabelledFigure::new("Warm starts", starts.warm.to_string())
                .of(format!("of {}", starts.total()))
        } else {
            LabelledFigure::new("Warm starts", "–")
        };
        let cpu = match self.peaks.cpu_p99() {
            Some(p99) => {
                LabelledFigure::new("CPU p99", cores_used(p99)).of(format!("of {}", self.cpus))
            }
            None => LabelledFigure::new("CPU p99", "–"),
        };
        vec![
            LabelledFigure::new(JOBS_HEADING, starts.total().to_string()),
            LabelledFigure::new("Slots busy", format!("{}%", self.busy)),
            LabelledFigure::new(
                "Waited p50 / p95",
                format!("{} / {}", duration(self.wait.p50), duration(self.wait.p95)),
            ),
            warm,
            cpu,
        ]
    }

    /// Its advice in a word or two, for a table cell: `Advice::word`, or `at ceiling` or `at max_memory` while that
    /// holds its `memory` where it is.
    pub fn advice_word(&self) -> String {
        match self.held().map(|hold| hold.by) {
            Some(MemoryBound::Ceiling { .. }) => "at ceiling".to_owned(),
            Some(MemoryBound::MaxMemory | MemoryBound::MinMemory) => "at max_memory".to_owned(),
            None => self.advice.word(),
        }
    }
}

impl JobSizing {
    /// What its jobs need, for a table cell, and what that means: `max 3G` with too few runs, `9G > cap` past its
    /// profile's cap, else `6G`.
    pub fn needs(&self) -> Toned {
        let (text, tone) = match self.advice {
            Advice::TooFew { .. } => (
                format!("max {}", ByteSize(self.peaks.memory.max)),
                Tone::Quiet,
            ),
            Advice::Raise { memory, .. } | Advice::SliceTooSmall { memory } => {
                (format!("{} > cap", ByteSize(memory)), Tone::Bad)
            }
            Advice::Keep { memory } | Advice::Lower { memory, .. } => {
                (ByteSize(memory).to_string(), Tone::Neutral)
            }
        };
        Toned { text, tone }
    }
}

impl Peaks {
    /// The CPU p99 of the runs at the profile's `cpus` now; `None` without one, where it would read 0.
    pub fn cpu_p99(&self) -> Option<u64> {
        (self.cpu_runs > 0).then_some(self.cpu.p99)
    }

    /// Which runs the CPU percentiles are over, for a profile at `cpus`, as every client says it: `of the 4 at 8
    /// CPUs`, or without one `no run at 8 CPUs yet`.
    pub fn cpu_runs_line(&self, cpus: u32) -> String {
        match self.cpu_runs {
            0 => format!("no run at {cpus} CPUs yet"),
            runs => format!("of the {runs} at {cpus} CPUs"),
        }
    }
}

impl Starts {
    /// Every job counted: warm and cold starts.
    pub fn total(&self) -> u32 {
        self.warm + self.cold
    }
}

/// What auto sizing does next with one profile at a given time, from `AutoPlan::profile_plan`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProfilePlan<'plan> {
    /// The next look makes this change, or would once `AutoPlan::blocked` is fixed.
    Next {
        /// The change.
        change: &'plan SizingChange,
        /// Whether `AutoPlan::blocked` keeps it from being made.
        blocked: bool,
    },
    /// A recent change holds it from any change until `hold.until`.
    Held {
        /// The hold.
        hold: &'plan SizingHold,
    },
    /// A recent change holds it from a lowering until `hold.lowered_after()`; a raise may come before.
    LowerHeld {
        /// The hold.
        hold: &'plan SizingHold,
    },
    /// Nothing: the advice asks for no change, and no hold is left.
    Nothing,
}

impl AutoPlan {
    /// The `cpus` and `slots` raises `profile`'s jobs ask for and the next look cannot make, each a line of its own
    /// beside what it does next, which can still change its memory or slots: `No CPU raise: 3 runs of … the cap holds
    /// them back; …`, then `No slot raise: 12 jobs waited 300s for a slot …; it is at its max_slots, 12`.
    pub fn refusals(&self, profile: &str) -> Vec<String> {
        let lines = |refused: &[SizingRefused], what: &str| -> Vec<String> {
            refused
                .iter()
                .filter(|refused| refused.profile == profile)
                .map(|refused| format!("No {what} raise: {}", refused.reason))
                .collect()
        };
        let mut refusals = lines(&self.refused, "CPU");
        refusals.extend(lines(&self.refused_slots, "slot"));
        refusals
    }

    /// What keeps every look from changing anything, as clients say it over the profiles: `No look changes anything
    /// now: the file changed on disk since runnerd read it; …`. `None` while the next look may write its changes.
    pub fn blocked_line(&self) -> Option<String> {
        self.blocked
            .as_ref()
            .map(|blocked| format!("No look changes anything now: {blocked}"))
    }

    /// What it does next with `profile` at `now`: a hold whose time has passed holds nothing, however old the plan.
    pub fn profile_plan(&self, profile: &str, now: u64) -> ProfilePlan<'_> {
        if let Some(change) = self.next.iter().find(|change| change.profile == profile) {
            return ProfilePlan::Next {
                change,
                blocked: self.blocked.is_some(),
            };
        }
        match self.held.iter().find(|hold| hold.profile == profile) {
            Some(hold) if now < hold.until => ProfilePlan::Held { hold },
            Some(hold) if now < hold.lowered_after() => ProfilePlan::LowerHeld { hold },
            _ => ProfilePlan::Nothing,
        }
    }
}

impl ProfilePlan<'_> {
    /// When what it says ends: the hold's end, for a held profile.
    pub fn until(&self) -> Option<u64> {
        match self {
            ProfilePlan::Held { hold } => Some(hold.until),
            ProfilePlan::LowerHeld { hold } => Some(hold.lowered_after()),
            ProfilePlan::Next { .. } | ProfilePlan::Nothing => None,
        }
    }

    /// What it does, as the lead of its line, before `until` when it has one: `Next look, within 5 minutes: memory
    /// 9G → 6.75G, slots 2`, `Once that is fixed: …`, `No change`, `No lowering` or `Nothing to change`.
    pub fn headline(&self, plan: &AutoPlan) -> String {
        match self {
            ProfilePlan::Next {
                change,
                blocked: true,
            } => format!("Once that is fixed: {}", change.line()),
            ProfilePlan::Next { change, .. } => format!(
                "Next look, within {}: {}",
                super::period(plan.every),
                change.line()
            ),
            ProfilePlan::Held { .. } => "No change".to_owned(),
            ProfilePlan::LowerHeld { .. } => "No lowering".to_owned(),
            ProfilePlan::Nothing => "Nothing to change".to_owned(),
        }
    }

    /// Why, after when the hold's change was made for a held profile: the change's reason, `the interval holds it
    /// until then`, `a raise may come before then`, or the advice's line.
    pub fn reason(&self, sizing: &Sizing, profile: &ProfileSizing) -> String {
        match self {
            ProfilePlan::Next { change, .. } => change.reason.clone(),
            ProfilePlan::Held { .. } => "the interval holds it until then".to_owned(),
            ProfilePlan::LowerHeld { .. } => "a raise may come before then".to_owned(),
            ProfilePlan::Nothing => sizing.advice_line(profile),
        }
    }

    /// When the change that holds it was made, for a held profile.
    pub fn changed(&self) -> Option<u64> {
        match self {
            ProfilePlan::Held { hold } | ProfilePlan::LowerHeld { hold } => Some(hold.changed),
            ProfilePlan::Next { .. } | ProfilePlan::Nothing => None,
        }
    }
}

#[cfg(test)]
mod tests;