1use std::fmt;
18
19use minicbor::{Decode, Encode};
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
23pub enum MachinePart {
24 Kernel,
26 Limits,
28 Affinity,
30 Memory,
32 Filesystem,
35 Disk,
37}
38
39impl MachinePart {
40 pub const ALL: [Self; 6] = [
42 Self::Kernel,
43 Self::Limits,
44 Self::Affinity,
45 Self::Memory,
46 Self::Filesystem,
47 Self::Disk,
48 ];
49
50 #[must_use]
52 pub const fn name(self) -> &'static str {
53 match self {
54 Self::Kernel => "kernel",
55 Self::Limits => "limits",
56 Self::Affinity => "affinity",
57 Self::Memory => "memory",
58 Self::Filesystem => "filesystem",
59 Self::Disk => "disk",
60 }
61 }
62
63 #[must_use]
65 pub fn from_name(name: &str) -> Option<Self> {
66 Self::ALL.into_iter().find(|part| part.name() == name)
67 }
68
69 #[must_use]
72 pub fn parts(names: &[String]) -> Vec<Self> {
73 names
74 .iter()
75 .filter_map(|name| Self::from_name(name))
76 .collect()
77 }
78
79 #[must_use]
82 pub fn names_text() -> String {
83 let names: Vec<&str> = Self::ALL.iter().map(|part| part.name()).collect();
84 match names.split_last() {
85 Some((last, rest)) => format!("{} and {last}", rest.join(", ")),
86 None => String::new(),
87 }
88 }
89}
90
91impl fmt::Display for MachinePart {
92 fn fmt(
93 &self,
94 f: &mut fmt::Formatter<'_>,
95 ) -> fmt::Result {
96 f.write_str(self.name())
97 }
98}
99
100#[derive(Debug, Clone, PartialEq, Eq, Hash, Encode, Decode)]
102pub struct KernelRecord {
103 #[n(0)]
105 pub release: String,
106 #[n(1)]
108 pub version: String,
109}
110
111#[derive(Debug, Clone, PartialEq, Eq, Hash, Encode, Decode)]
113pub struct LimitRecord {
114 #[n(0)]
116 pub resource: String,
117 #[n(1)]
119 pub soft: Option<u64>,
120 #[n(2)]
122 pub hard: Option<u64>,
123}
124
125#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Encode, Decode)]
127pub struct MemoryRecord {
128 #[n(0)]
130 pub total: u64,
131 #[n(1)]
133 pub available: u64,
134}
135
136#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Encode, Decode)]
138pub struct FileSystemRecord {
139 #[n(0)]
141 pub kind: u64,
142 #[n(1)]
144 pub flags: u64,
145}
146
147#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Encode, Decode)]
150pub struct DiskRecord {
151 #[n(0)]
153 pub size: u64,
154 #[n(1)]
156 pub free: u64,
157}
158
159#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, Encode, Decode)]
163pub struct MachineStateRecord {
164 #[n(0)]
166 pub kernel: Option<KernelRecord>,
167 #[n(1)]
169 pub limits: Option<Vec<LimitRecord>>,
170 #[n(2)]
172 pub affinity: Option<Vec<u32>>,
173 #[n(3)]
175 pub memory: Option<MemoryRecord>,
176 #[n(4)]
179 pub filesystem: Option<FileSystemRecord>,
180 #[n(5)]
182 pub disk: Option<DiskRecord>,
183}
184
185fn bytes(number: u64) -> String {
187 format!("{number} bytes")
188}
189
190fn limit_text(limit: Option<u64>) -> String {
192 limit.map_or_else(|| "unlimited".to_owned(), |limit| limit.to_string())
193}
194
195fn cpu_list(cpus: &[u32]) -> String {
198 let mut ranges: Vec<(u32, u32)> = Vec::new();
199 for &cpu in cpus {
200 match ranges.last_mut() {
201 Some((_, last)) if last.checked_add(1) == Some(cpu) => *last = cpu,
202 _ => ranges.push((cpu, cpu)),
203 }
204 }
205 if ranges.is_empty() {
206 return "none".to_owned();
207 }
208 let shown: Vec<String> = ranges
209 .iter()
210 .map(|&(first, last)| {
211 if first == last {
212 first.to_string()
213 } else {
214 format!("{first}-{last}")
215 }
216 })
217 .collect();
218 shown.join(",")
219}
220
221impl MachineStateRecord {
222 #[must_use]
225 pub fn values(
226 &self,
227 part: MachinePart,
228 ) -> Option<Vec<(String, String)>> {
229 let named = |name: &str, value: String| (name.to_owned(), value);
230 match part {
231 MachinePart::Kernel => {
232 self.kernel.as_ref().map(|kernel| {
233 vec![
234 named("kernel release", kernel.release.clone()),
235 named("kernel version", kernel.version.clone()),
236 ]
237 })
238 },
239 MachinePart::Limits => {
240 self.limits.as_ref().map(|limits| {
241 limits
242 .iter()
243 .flat_map(|limit| {
244 [
245 (
246 format!("soft limit of {}", limit.resource),
247 limit_text(limit.soft),
248 ),
249 (
250 format!("hard limit of {}", limit.resource),
251 limit_text(limit.hard),
252 ),
253 ]
254 })
255 .collect()
256 })
257 },
258 MachinePart::Affinity => {
259 self.affinity
260 .as_ref()
261 .map(|cpus| vec![named("CPUs", cpu_list(cpus))])
262 },
263 MachinePart::Memory => {
264 self.memory.map(|memory| {
265 vec![
266 named("total memory", bytes(memory.total)),
267 named("available memory", bytes(memory.available)),
268 ]
269 })
270 },
271 MachinePart::Filesystem => {
272 self.filesystem.map(|filesystem| {
273 vec![
274 named("file system type", format!("{:#x}", filesystem.kind)),
275 named("mount flags", format!("{:#x}", filesystem.flags)),
276 ]
277 })
278 },
279 MachinePart::Disk => {
280 self.disk.map(|disk| {
281 vec![
282 named("file system size", bytes(disk.size)),
283 named("free space", bytes(disk.free)),
284 ]
285 })
286 },
287 }
288 }
289
290 #[must_use]
294 pub fn text(
295 &self,
296 part: MachinePart,
297 ) -> String {
298 self.values(part).map_or_else(
299 || "unknown".to_owned(),
300 |values| {
301 let shown: Vec<String> = values
302 .iter()
303 .map(|(name, value)| format!("{name} {value}"))
304 .collect();
305 shown.join(", ")
306 },
307 )
308 }
309}
310
311#[derive(Debug, Clone, PartialEq, Eq, Hash, Encode, Decode)]
313pub struct MachineChange {
314 #[n(0)]
317 pub value: String,
318 #[n(1)]
320 pub old: String,
321 #[n(2)]
323 pub new: String,
324}
325
326impl fmt::Display for MachineChange {
327 fn fmt(
328 &self,
329 f: &mut fmt::Formatter<'_>,
330 ) -> fmt::Result {
331 write!(f, "{} from {} to {}", self.value, self.old, self.new)
332 }
333}
334
335fn value_of(
337 values: &[(String, String)],
338 name: &str,
339) -> String {
340 values
341 .iter()
342 .find(|(each, _)| each == name)
343 .map_or_else(|| "none".to_owned(), |(_, value)| value.clone())
344}
345
346#[must_use]
353pub fn machine_changes(
354 parts: &[MachinePart],
355 old: &MachineStateRecord,
356 new: &MachineStateRecord,
357) -> Vec<MachineChange> {
358 let mut changes = Vec::new();
359 for &part in parts {
360 let (Some(old_values), Some(new_values)) = (old.values(part), new.values(part)) else {
361 let (old_text, new_text) = (old.text(part), new.text(part));
362 if old_text != new_text {
363 changes.push(MachineChange {
364 value: part.name().to_owned(),
365 old: old_text,
366 new: new_text,
367 });
368 }
369 continue;
370 };
371 let mut names: Vec<&str> = old_values.iter().map(|(name, _)| name.as_str()).collect();
372 for (name, _) in &new_values {
373 if !names.contains(&name.as_str()) {
374 names.push(name);
375 }
376 }
377 for name in names {
378 let (old_value, new_value) = (value_of(&old_values, name), value_of(&new_values, name));
379 if old_value != new_value {
380 changes.push(MachineChange {
381 value: name.to_owned(),
382 old: old_value,
383 new: new_value,
384 });
385 }
386 }
387 }
388 changes
389}
390
391#[must_use]
394pub fn machine_changes_text(changes: &[MachineChange]) -> String {
395 if changes.is_empty() {
396 return "nothing".to_owned();
397 }
398 let shown: Vec<String> = changes.iter().map(ToString::to_string).collect();
399 shown.join(", ")
400}
401
402#[cfg(test)]
404#[allow(
405 clippy::disallowed_macros,
406 clippy::disallowed_methods,
407 reason = "test code: the tests assert and lock"
408)]
409mod tests {
410 use super::*;
411
412 fn state() -> MachineStateRecord {
414 MachineStateRecord {
415 kernel: Some(KernelRecord {
416 release: "6.12.0".to_owned(),
417 version: "#1 SMP".to_owned(),
418 }),
419 limits: Some(vec![
420 LimitRecord {
421 resource: "cpu".to_owned(),
422 soft: None,
423 hard: None,
424 },
425 LimitRecord {
426 resource: "nofile".to_owned(),
427 soft: Some(1_024),
428 hard: Some(524_288),
429 },
430 ]),
431 affinity: Some(vec![0, 1, 2, 3, 6]),
432 memory: Some(MemoryRecord {
433 total: 8_000,
434 available: 4_000,
435 }),
436 filesystem: Some(FileSystemRecord {
437 kind: 0xEF53,
438 flags: 0x1020,
439 }),
440 disk: Some(DiskRecord {
441 size: 100_000,
442 free: 40_000,
443 }),
444 }
445 }
446
447 #[test]
450 fn parts_have_their_names() {
451 let names: Vec<&str> = MachinePart::ALL.iter().map(|part| part.name()).collect();
452 assert_eq!(names, [
453 "kernel",
454 "limits",
455 "affinity",
456 "memory",
457 "filesystem",
458 "disk"
459 ]);
460 for part in MachinePart::ALL {
461 assert_eq!(MachinePart::from_name(part.name()), Some(part));
462 assert_eq!(part.to_string(), part.name());
463 }
464 assert_eq!(MachinePart::from_name("cpu"), None);
465 assert_eq!(MachinePart::from_name("Kernel"), None);
466 assert_eq!(
467 MachinePart::parts(&["disk".to_owned(), "x".to_owned(), "kernel".to_owned()]),
468 [MachinePart::Disk, MachinePart::Kernel]
469 );
470 assert_eq!(
471 MachinePart::names_text(),
472 "kernel, limits, affinity, memory, filesystem and disk"
473 );
474 }
475
476 #[test]
479 fn every_part_reads_as_text() {
480 let state = state();
481 let shown: Vec<String> = MachinePart::ALL
482 .iter()
483 .map(|part| state.text(*part))
484 .collect();
485 assert_eq!(shown, [
486 "kernel release 6.12.0, kernel version #1 SMP",
487 "soft limit of cpu unlimited, hard limit of cpu unlimited, soft limit of nofile 1024, \
488 hard limit of nofile 524288",
489 "CPUs 0-3,6",
490 "total memory 8000 bytes, available memory 4000 bytes",
491 "file system type 0xef53, mount flags 0x1020",
492 "file system size 100000 bytes, free space 40000 bytes",
493 ]);
494 let unknown = MachineStateRecord::default();
495 for part in MachinePart::ALL {
496 assert_eq!(unknown.text(part), "unknown");
497 assert_eq!(unknown.values(part), None);
498 }
499 let none = MachineStateRecord {
500 affinity: Some(Vec::new()),
501 ..MachineStateRecord::default()
502 };
503 assert_eq!(none.text(MachinePart::Affinity), "CPUs none");
504 }
505
506 #[test]
509 fn only_the_named_parts_are_compared_value_by_value() {
510 let old = state();
511 let mut new = state();
512 new.kernel = Some(KernelRecord {
513 release: "6.13.0".to_owned(),
514 version: "#1 SMP".to_owned(),
515 });
516 new.memory = Some(MemoryRecord {
517 total: 8_000,
518 available: 3_000,
519 });
520 if let Some(limits) = &mut new.limits {
521 limits.retain(|limit| limit.resource != "cpu");
522 }
523 new.affinity = Some(vec![0, 1]);
524 new.disk = None;
525 assert_eq!(machine_changes(&[], &old, &new), []);
526 assert_eq!(machine_changes(&[MachinePart::Filesystem], &old, &new), []);
527 let change = |value: &str, old: &str, new: &str| {
528 MachineChange {
529 value: value.to_owned(),
530 old: old.to_owned(),
531 new: new.to_owned(),
532 }
533 };
534 assert_eq!(machine_changes(&MachinePart::ALL, &old, &new), [
535 change("kernel release", "6.12.0", "6.13.0"),
536 change("soft limit of cpu", "unlimited", "none"),
537 change("hard limit of cpu", "unlimited", "none"),
538 change("CPUs", "0-3,6", "0-1"),
539 change("available memory", "4000 bytes", "3000 bytes"),
540 change(
541 "disk",
542 "file system size 100000 bytes, free space 40000 bytes",
543 "unknown"
544 ),
545 ]);
546 assert_eq!(machine_changes(&MachinePart::ALL, &old, &old), []);
547 let unknown = MachineStateRecord::default();
548 assert_eq!(machine_changes(&MachinePart::ALL, &unknown, &unknown), []);
549 }
550
551 #[test]
554 fn changes_read_as_text() {
555 let changes = [
556 MachineChange {
557 value: "kernel release".to_owned(),
558 old: "6.12.0".to_owned(),
559 new: "6.13.0".to_owned(),
560 },
561 MachineChange {
562 value: "CPUs".to_owned(),
563 old: "0-3".to_owned(),
564 new: "0".to_owned(),
565 },
566 ];
567 assert_eq!(
568 machine_changes_text(&changes),
569 "kernel release from 6.12.0 to 6.13.0, CPUs from 0-3 to 0"
570 );
571 assert_eq!(machine_changes_text(&[]), "nothing");
572 }
573
574 #[test]
577 fn states_and_changes_encode_deterministically_and_round_trip() {
578 for state in [state(), MachineStateRecord::default()] {
579 let first = minicbor::to_vec(&state).unwrap();
580 assert_eq!(first, minicbor::to_vec(state.clone()).unwrap());
581 assert_eq!(
582 minicbor::decode::<MachineStateRecord>(&first).unwrap(),
583 state
584 );
585 }
586 assert_eq!(minicbor::to_vec(state()).unwrap().first(), Some(&0x86));
587 let change = MachineChange {
588 value: "CPUs".to_owned(),
589 old: "0".to_owned(),
590 new: "1".to_owned(),
591 };
592 let bytes = minicbor::to_vec(&change).unwrap();
593 assert_eq!(bytes, b"\x83\x64CPUs\x610\x611");
594 assert_eq!(minicbor::decode::<MachineChange>(&bytes).unwrap(), change);
595 }
596}