1use super::{
6 Advice, AutoPlan, JobSizing, MemoryBound, MemoryHold, PAGE_CACHE_ROOM, Peaks, ProfileSizing,
7 Sizing, SizingChange, SizingHold, SizingRefused, Starts,
8};
9use crate::api::{Check, CheckStatus, Tone, Toned};
10use crate::config::ByteSize;
11
12pub const GRANULE: u64 = 256 << 20;
14
15pub const SAMPLE_INTERVAL: u64 = 2;
18
19pub fn need(peak: u64, margin: u32) -> u64 {
23 let room = (peak.saturating_mul(u64::from(margin)) / 100).max(PAGE_CACHE_ROOM);
24 peak.saturating_add(room)
25 .div_ceil(GRANULE)
26 .saturating_mul(GRANULE)
27 .max(GRANULE)
28}
29
30pub fn sampled_note(interval: u64) -> String {
33 format!("memory peaks are sampled every {interval} s; spikes shorter than that do not show")
34}
35
36#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct Need {
39 pub memory: u64,
41 pub reason: String,
43}
44
45impl Sizing {
46 pub fn need(&self, profile: &ProfileSizing) -> Need {
49 let peaks = &profile.peaks;
50 let memory = match profile.advice {
51 _ if let Some(hold) = profile.hold => hold.need,
52 Advice::Keep { memory }
53 | Advice::Lower { memory, .. }
54 | Advice::Raise { memory, .. }
55 | Advice::SliceTooSmall { memory } => memory,
56 Advice::TooFew { .. } => need(peaks.memory.max, self.margin),
57 };
58 Need {
59 memory,
60 reason: self.need_reason(peaks),
61 }
62 }
63
64 pub(crate) fn need_reason(&self, peaks: &Peaks) -> String {
67 if peaks.memory.max * u64::from(self.margin) / 100 >= PAGE_CACHE_ROOM {
68 format!("its largest peak + {}%", self.margin)
69 } else {
70 format!(
71 "its largest peak + {} for page cache",
72 ByteSize(PAGE_CACHE_ROOM)
73 )
74 }
75 }
76
77 pub fn method_line(&self) -> String {
81 format!(
82 "peaks are sampled every {} s, so a shorter spike goes unseen: advice sizes for the largest + {}%, at \
83 least {} for page cache, rounded up to {}, once a profile ran {} jobs",
84 self.sample_interval,
85 self.margin,
86 ByteSize(PAGE_CACHE_ROOM),
87 ByteSize(GRANULE),
88 self.min_jobs
89 )
90 }
91
92 pub fn method_parts(&self) -> Vec<String> {
95 vec![
96 format!("peaks sampled every {} s", self.sample_interval),
97 format!(
98 "+{}%, at least {}, in {} steps",
99 self.margin,
100 ByteSize(PAGE_CACHE_ROOM),
101 ByteSize(GRANULE)
102 ),
103 format!("advice after {} jobs", self.min_jobs),
104 ]
105 }
106
107 pub fn covered(&self) -> u64 {
109 self.until.saturating_sub(self.since)
110 }
111
112 pub fn doctor_check(&self) -> Check {
115 let changes: Vec<_> = self
116 .profiles
117 .iter()
118 .filter(|profile| {
119 profile.advice.change().is_some()
120 || matches!(profile.advice, Advice::SliceTooSmall { .. })
121 })
122 .collect();
123 let raise = changes
124 .iter()
125 .any(|profile| profile.advice.tone() == Tone::Bad);
126 let detail = if changes.is_empty() {
127 let too_few = self
128 .profiles
129 .iter()
130 .any(|profile| matches!(profile.advice, Advice::TooFew { .. }));
131 if too_few {
132 format!(
133 "some profiles ran fewer than {} jobs; runnerctl sizing shows their peaks",
134 self.min_jobs
135 )
136 } else {
137 format!(
138 "every profile's memory fits its jobs' largest peak + {}%, at least {} for page cache",
139 self.margin,
140 ByteSize(PAGE_CACHE_ROOM)
141 )
142 }
143 } else {
144 changes
145 .iter()
146 .map(|profile| format!("{}: {}", profile.name, self.advice_line(profile)))
147 .collect::<Vec<_>>()
148 .join("; ")
149 };
150 Check {
151 name: "sizing".to_owned(),
152 status: if raise {
153 CheckStatus::Warn
154 } else {
155 CheckStatus::Info
156 },
157 detail,
158 fix: (!changes.is_empty()).then(|| {
159 changes
160 .iter()
161 .map(|profile| match profile.advice {
162 Advice::SliceTooSmall { .. } => match profile.held().map(|hold| hold.by) {
163 Some(MemoryBound::Ceiling { .. }) => format!(
164 "raise [host] memory_ceiling if the host can grow further, then: runnerctl \
165 sizing apply {}",
166 profile.name
167 ),
168 Some(MemoryBound::MaxMemory | MemoryBound::MinMemory) => format!(
169 "raise max_memory in [profiles.{0}], then: runnerctl sizing apply {0}",
170 profile.name
171 ),
172 None => format!(
173 "raise MemoryMax in the slice's unit file, sudo systemctl daemon-reload, then: \
174 runnerctl sizing apply {}",
175 profile.name
176 ),
177 },
178 _ => format!("runnerctl sizing apply {}", profile.name),
179 })
180 .collect::<Vec<_>>()
181 .join("\n")
182 }),
183 }
184 }
185}
186
187impl Advice {
188 pub fn tone(&self) -> Tone {
191 match self {
192 Advice::Raise { .. } | Advice::SliceTooSmall { .. } => Tone::Bad,
193 Advice::Lower { .. } => Tone::Warn,
194 Advice::Keep { .. } => Tone::Good,
195 Advice::TooFew { .. } => Tone::Quiet,
196 }
197 }
198
199 pub fn word(&self) -> String {
201 match *self {
202 Advice::TooFew { .. } => "too few".to_owned(),
203 Advice::Keep { .. } => "keep".to_owned(),
204 Advice::SliceTooSmall { .. } => "grow slice".to_owned(),
205 Advice::Lower { memory, slots } | Advice::Raise { memory, slots } => {
206 format!("{} × {slots}", ByteSize(memory))
207 }
208 }
209 }
210}
211
212impl ProfileSizing {
213 pub fn held(&self) -> Option<MemoryHold> {
216 self.hold.filter(|hold| {
217 matches!(self.advice, Advice::SliceTooSmall { .. })
218 && hold.by != MemoryBound::MinMemory
219 && self.memory >= hold.bound
220 })
221 }
222
223 pub fn advice_word(&self) -> String {
226 match self.held().map(|hold| hold.by) {
227 Some(MemoryBound::Ceiling { .. }) => "at ceiling".to_owned(),
228 Some(MemoryBound::MaxMemory | MemoryBound::MinMemory) => "at max_memory".to_owned(),
229 None => self.advice.word(),
230 }
231 }
232}
233
234impl JobSizing {
235 pub fn needs(&self) -> Toned {
238 let (text, tone) = match self.advice {
239 Advice::TooFew { .. } => (
240 format!("max {}", ByteSize(self.peaks.memory.max)),
241 Tone::Quiet,
242 ),
243 Advice::Raise { memory, .. } | Advice::SliceTooSmall { memory } => {
244 (format!("{} > cap", ByteSize(memory)), Tone::Bad)
245 }
246 Advice::Keep { memory } | Advice::Lower { memory, .. } => {
247 (ByteSize(memory).to_string(), Tone::Neutral)
248 }
249 };
250 Toned { text, tone }
251 }
252}
253
254impl Peaks {
255 pub fn cpu_p99(&self) -> Option<u64> {
257 (self.cpu_runs > 0).then_some(self.cpu.p99)
258 }
259
260 pub fn cpu_runs_line(&self, cpus: u32) -> String {
263 match self.cpu_runs {
264 0 => format!("no run at {cpus} CPUs yet"),
265 runs => format!("of the {runs} at {cpus} CPUs"),
266 }
267 }
268}
269
270impl Starts {
271 pub fn total(&self) -> u32 {
273 self.warm + self.cold
274 }
275}
276
277#[derive(Debug, Clone, Copy, PartialEq, Eq)]
279pub enum ProfilePlan<'plan> {
280 Next {
282 change: &'plan SizingChange,
284 blocked: bool,
286 },
287 Held {
289 hold: &'plan SizingHold,
291 },
292 LowerHeld {
294 hold: &'plan SizingHold,
296 },
297 Nothing,
299}
300
301impl AutoPlan {
302 pub fn refusals(&self, profile: &str) -> Vec<String> {
306 let lines = |refused: &[SizingRefused], what: &str| -> Vec<String> {
307 refused
308 .iter()
309 .filter(|refused| refused.profile == profile)
310 .map(|refused| format!("No {what} raise: {}", refused.reason))
311 .collect()
312 };
313 let mut refusals = lines(&self.refused, "CPU");
314 refusals.extend(lines(&self.refused_slots, "slot"));
315 refusals
316 }
317
318 pub fn blocked_line(&self) -> Option<String> {
321 self.blocked
322 .as_ref()
323 .map(|blocked| format!("No look changes anything now: {blocked}"))
324 }
325
326 pub fn profile_plan(&self, profile: &str, now: u64) -> ProfilePlan<'_> {
328 if let Some(change) = self.next.iter().find(|change| change.profile == profile) {
329 return ProfilePlan::Next {
330 change,
331 blocked: self.blocked.is_some(),
332 };
333 }
334 match self.held.iter().find(|hold| hold.profile == profile) {
335 Some(hold) if now < hold.until => ProfilePlan::Held { hold },
336 Some(hold) if now < hold.lowered_after() => ProfilePlan::LowerHeld { hold },
337 _ => ProfilePlan::Nothing,
338 }
339 }
340}
341
342impl ProfilePlan<'_> {
343 pub fn until(&self) -> Option<u64> {
345 match self {
346 ProfilePlan::Held { hold } => Some(hold.until),
347 ProfilePlan::LowerHeld { hold } => Some(hold.lowered_after()),
348 ProfilePlan::Next { .. } | ProfilePlan::Nothing => None,
349 }
350 }
351
352 pub fn headline(&self, plan: &AutoPlan) -> String {
355 match self {
356 ProfilePlan::Next {
357 change,
358 blocked: true,
359 } => format!("Once that is fixed: {}", change.line()),
360 ProfilePlan::Next { change, .. } => format!(
361 "Next look, within {}: {}",
362 super::period(plan.every),
363 change.line()
364 ),
365 ProfilePlan::Held { .. } => "No change".to_owned(),
366 ProfilePlan::LowerHeld { .. } => "No lowering".to_owned(),
367 ProfilePlan::Nothing => "Nothing to change".to_owned(),
368 }
369 }
370
371 pub fn reason(&self, sizing: &Sizing, profile: &ProfileSizing) -> String {
374 match self {
375 ProfilePlan::Next { change, .. } => change.reason.clone(),
376 ProfilePlan::Held { .. } => "the interval holds it until then".to_owned(),
377 ProfilePlan::LowerHeld { .. } => "a raise may come before then".to_owned(),
378 ProfilePlan::Nothing => sizing.advice_line(profile),
379 }
380 }
381
382 pub fn changed(&self) -> Option<u64> {
384 match self {
385 ProfilePlan::Held { hold } | ProfilePlan::LowerHeld { hold } => Some(hold.changed),
386 ProfilePlan::Next { .. } | ProfilePlan::Nothing => None,
387 }
388 }
389}
390
391#[cfg(test)]
392mod tests;