1use std::fmt;
13use std::path::{Path, PathBuf};
14
15use serde::{Deserialize, Serialize};
16
17use crate::vmm::initramfs::InitrdCompression;
18
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
38#[serde(rename_all = "lowercase", tag = "type")]
39#[non_exhaustive]
40pub enum KernelSource {
41 Tarball,
44 Git {
46 git_hash: Option<String>,
48 #[serde(rename = "ref")]
50 git_ref: Option<String>,
51 },
52 Local {
54 source_tree_path: Option<PathBuf>,
58 git_hash: Option<String>,
65 },
66 DistroPackage {
70 distro: String,
73 packages: Vec<String>,
76 },
77 LocalPackage {
81 packages: Vec<String>,
83 },
84}
85
86impl fmt::Display for KernelSource {
87 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88 match self {
89 KernelSource::Tarball => f.write_str("tarball"),
90 KernelSource::Git { .. } => f.write_str("git"),
91 KernelSource::Local { .. } => f.write_str("local"),
92 KernelSource::DistroPackage { .. } => f.write_str("distro-package"),
93 KernelSource::LocalPackage { .. } => f.write_str("local-package"),
94 }
95 }
96}
97
98impl KernelSource {
99 pub fn as_local_git_hash(&self) -> Option<&str> {
110 match self {
111 KernelSource::Local { git_hash, .. } => git_hash.as_deref(),
112 _ => None,
113 }
114 }
115
116 pub fn git(git_hash: impl Into<String>, git_ref: impl Into<String>) -> Self {
120 KernelSource::Git {
121 git_hash: Some(git_hash.into()),
122 git_ref: Some(git_ref.into()),
123 }
124 }
125}
126
127#[derive(Debug, Clone, Serialize, Deserialize)]
136#[non_exhaustive]
137pub struct KernelMetadata {
138 pub version: Option<String>,
143 pub source: KernelSource,
145 pub arch: String,
147 pub image_name: String,
149 pub config_hash: Option<String>,
151 pub built_at: String,
153 pub ktstr_kconfig_hash: Option<String>,
155 pub extra_kconfig_hash: Option<String>,
159 pub(crate) has_vmlinux: bool,
162 pub(crate) vmlinux_stripped: bool,
165 pub source_vmlinux_size: Option<u64>,
167 pub source_vmlinux_mtime_secs: Option<i64>,
170}
171
172impl KernelMetadata {
173 pub fn new(
175 source: KernelSource,
176 arch: impl Into<String>,
177 image_name: impl Into<String>,
178 built_at: impl Into<String>,
179 ) -> Self {
180 KernelMetadata {
181 version: None,
182 source,
183 arch: arch.into(),
184 image_name: image_name.into(),
185 config_hash: None,
186 built_at: built_at.into(),
187 ktstr_kconfig_hash: None,
188 extra_kconfig_hash: None,
189 has_vmlinux: false,
190 vmlinux_stripped: false,
191 source_vmlinux_size: None,
192 source_vmlinux_mtime_secs: None,
193 }
194 }
195
196 pub fn with_source_vmlinux_stat(mut self, size: u64, mtime_secs: i64) -> Self {
199 self.source_vmlinux_size = Some(size);
200 self.source_vmlinux_mtime_secs = Some(mtime_secs);
201 self
202 }
203
204 pub fn clear_source_vmlinux_stat(mut self) -> Self {
207 self.source_vmlinux_size = None;
208 self.source_vmlinux_mtime_secs = None;
209 self
210 }
211
212 pub fn with_version(mut self, version: impl Into<String>) -> Self {
214 self.version = Some(version.into());
215 self
216 }
217
218 pub fn clear_version(mut self) -> Self {
220 self.version = None;
221 self
222 }
223
224 pub fn with_config_hash(mut self, hash: impl Into<String>) -> Self {
226 self.config_hash = Some(hash.into());
227 self
228 }
229
230 pub fn clear_config_hash(mut self) -> Self {
232 self.config_hash = None;
233 self
234 }
235
236 pub fn with_ktstr_kconfig_hash(mut self, hash: impl Into<String>) -> Self {
238 self.ktstr_kconfig_hash = Some(hash.into());
239 self
240 }
241
242 pub fn clear_ktstr_kconfig_hash(mut self) -> Self {
244 self.ktstr_kconfig_hash = None;
245 self
246 }
247
248 pub fn with_extra_kconfig_hash(mut self, hash: impl Into<String>) -> Self {
250 self.extra_kconfig_hash = Some(hash.into());
251 self
252 }
253
254 pub fn clear_extra_kconfig_hash(mut self) -> Self {
256 self.extra_kconfig_hash = None;
257 self
258 }
259
260 pub fn has_vmlinux(&self) -> bool {
262 self.has_vmlinux
263 }
264
265 pub(crate) fn set_has_vmlinux(&mut self, value: bool) {
267 self.has_vmlinux = value;
268 }
269
270 pub fn vmlinux_stripped(&self) -> bool {
272 self.vmlinux_stripped
273 }
274
275 pub(crate) fn set_vmlinux_stripped(&mut self, value: bool) {
277 self.vmlinux_stripped = value;
278 }
279}
280
281#[derive(Debug, Clone)]
287#[non_exhaustive]
288pub struct CacheArtifacts<'a> {
289 pub image: &'a Path,
291 pub vmlinux: Option<&'a Path>,
294 pub modules: &'a [PathBuf],
301 pub config: Option<&'a Path>,
305}
306
307impl<'a> CacheArtifacts<'a> {
308 pub fn new(image: &'a Path) -> Self {
310 CacheArtifacts {
311 image,
312 vmlinux: None,
313 modules: &[],
314 config: None,
315 }
316 }
317
318 pub fn with_vmlinux(mut self, vmlinux: &'a Path) -> Self {
320 self.vmlinux = Some(vmlinux);
321 self
322 }
323
324 pub fn with_modules(mut self, modules: &'a [PathBuf]) -> Self {
326 self.modules = modules;
327 self
328 }
329
330 pub fn with_config(mut self, config: &'a Path) -> Self {
332 self.config = Some(config);
333 self
334 }
335}
336
337#[derive(Debug, Clone, PartialEq, Eq)]
340#[non_exhaustive]
341pub enum KconfigStatus {
342 Matches,
344 Stale {
346 cached: String,
348 current: String,
350 },
351 Untracked,
354}
355
356impl KconfigStatus {
357 pub fn is_stale(&self) -> bool {
359 matches!(self, Self::Stale { .. })
360 }
361
362 pub fn is_untracked(&self) -> bool {
364 matches!(self, Self::Untracked)
365 }
366}
367
368impl fmt::Display for KconfigStatus {
369 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
370 match self {
371 KconfigStatus::Matches => f.write_str("matches"),
372 KconfigStatus::Stale { .. } => f.write_str("stale"),
373 KconfigStatus::Untracked => f.write_str("untracked"),
374 }
375 }
376}
377
378#[derive(Debug)]
382#[non_exhaustive]
383pub struct CacheEntry {
384 pub key: String,
386 pub path: PathBuf,
388 pub metadata: KernelMetadata,
390}
391
392impl CacheEntry {
393 pub fn image_path(&self) -> PathBuf {
395 self.path.join(&self.metadata.image_name)
396 }
397
398 pub fn vmlinux_path(&self) -> Option<PathBuf> {
401 self.metadata.has_vmlinux.then(|| self.path.join("vmlinux"))
402 }
403
404 pub fn disk_template_path(&self) -> PathBuf {
407 self.path.join("disk-template.img")
408 }
409
410 pub fn boot_modules(&self) -> Vec<PathBuf> {
415 ordered_boot_modules_in(&self.path.join("modules"))
416 }
417
418 pub fn kconfig_status(&self, current_hash: &str) -> KconfigStatus {
420 match self.metadata.ktstr_kconfig_hash.as_deref() {
421 None => KconfigStatus::Untracked,
422 Some(h) if h == current_hash => KconfigStatus::Matches,
423 Some(h) => KconfigStatus::Stale {
424 cached: h.to_string(),
425 current: current_hash.to_string(),
426 },
427 }
428 }
429
430 pub fn has_extra_kconfig(&self) -> bool {
433 self.metadata.extra_kconfig_hash.is_some()
434 }
435}
436
437pub fn ordered_boot_modules_in(modules_dir: &Path) -> Vec<PathBuf> {
442 let Ok(rd) = std::fs::read_dir(modules_dir) else {
443 return Vec::new();
444 };
445 let mut entries: Vec<PathBuf> = rd
446 .flatten()
447 .filter(|e| e.file_type().map(|t| t.is_file()).unwrap_or(false))
448 .map(|e| e.path())
449 .collect();
450 entries.sort();
451 entries
452}
453
454pub fn boot_modules_for_image(image: &Path) -> Vec<PathBuf> {
461 match image.parent() {
462 Some(dir) => ordered_boot_modules_in(&dir.join("modules")),
463 None => Vec::new(),
464 }
465}
466
467pub fn initrd_compression_for_image(image: &Path) -> InitrdCompression {
477 let Some(config) = image.parent().map(|d| d.join("config")) else {
478 return InitrdCompression::Lz4;
479 };
480 let Ok(text) = std::fs::read_to_string(&config) else {
481 return InitrdCompression::Lz4;
482 };
483 initrd_compression_for_config(&text)
484}
485
486pub(crate) fn kernel_config_include_for_image(image: &Path) -> Option<(String, PathBuf)> {
495 let entry_dir = image.parent()?;
496 let metadata = super::housekeeping::read_metadata(entry_dir).ok()?;
497 if image.file_name()? != std::ffi::OsStr::new(&metadata.image_name) {
498 return None;
499 }
500 let release = metadata.version.as_deref()?;
501 let mut components = Path::new(release).components();
502 if release.is_empty()
503 || release.len() > 64
504 || !matches!(components.next(), Some(std::path::Component::Normal(_)))
505 || components.next().is_some()
506 {
507 return None;
508 }
509 let config = entry_dir.join("config");
510 std::fs::metadata(&config)
511 .ok()
512 .filter(|metadata| metadata.is_file())?;
513 Some((format!("boot/config-{release}"), config))
514}
515
516fn initrd_compression_for_config(text: &str) -> InitrdCompression {
519 let enabled = |opt: &str| text.lines().any(|l| l.strip_prefix(opt) == Some("=y"));
521 if enabled("CONFIG_RD_LZ4") {
522 InitrdCompression::Lz4
523 } else if enabled("CONFIG_RD_ZSTD") {
524 InitrdCompression::Zstd
525 } else if enabled("CONFIG_RD_GZIP") {
526 InitrdCompression::Gzip
527 } else {
528 InitrdCompression::Uncompressed
529 }
530}
531
532#[derive(Debug)]
535#[non_exhaustive]
536pub enum ListedEntry {
537 Valid(Box<CacheEntry>),
540 Corrupt {
542 key: String,
544 path: PathBuf,
546 reason: String,
549 },
550}
551
552impl ListedEntry {
553 pub fn key(&self) -> &str {
555 match self {
556 ListedEntry::Valid(e) => &e.key,
557 ListedEntry::Corrupt { key, .. } => key,
558 }
559 }
560
561 pub fn path(&self) -> &Path {
563 match self {
564 ListedEntry::Valid(e) => &e.path,
565 ListedEntry::Corrupt { path, .. } => path,
566 }
567 }
568
569 pub fn as_valid(&self) -> Option<&CacheEntry> {
572 match self {
573 ListedEntry::Valid(e) => Some(e.as_ref()),
574 ListedEntry::Corrupt { .. } => None,
575 }
576 }
577
578 pub fn error_kind(&self) -> Option<&'static str> {
581 match self {
582 ListedEntry::Valid(_) => None,
583 ListedEntry::Corrupt { reason, .. } => Some(classify_corrupt_reason(reason)),
584 }
585 }
586}
587
588pub(crate) const IMAGE_MISSING_SUFFIX: &str = " missing from entry directory";
595
596pub(crate) const IMAGE_MISSING_PREFIX: &str = "image file ";
600
601pub(crate) fn format_image_missing_reason(image_name: &str) -> String {
615 format!("{IMAGE_MISSING_PREFIX}{image_name}{IMAGE_MISSING_SUFFIX}")
616}
617
618pub(crate) fn classify_corrupt_reason(reason: &str) -> &'static str {
660 if reason == "metadata.json missing" {
661 "missing"
662 } else if reason.starts_with("metadata.json unreadable: ") {
663 "unreadable"
664 } else if reason.starts_with("metadata.json schema drift: ") {
665 "schema_drift"
666 } else if reason.starts_with("metadata.json malformed: ") {
667 "malformed"
668 } else if reason.starts_with("metadata.json truncated: ") {
669 "truncated"
670 } else if reason.starts_with("metadata.json parse error: ") {
671 "parse_error"
684 } else if reason.starts_with(IMAGE_MISSING_PREFIX)
685 && reason.ends_with(IMAGE_MISSING_SUFFIX)
686 && reason.len() > IMAGE_MISSING_PREFIX.len() + IMAGE_MISSING_SUFFIX.len()
687 {
688 "image_missing"
689 } else {
690 "unknown"
691 }
692}
693
694#[cfg(test)]
695mod tests {
696 use super::*;
697 use crate::cache::shared_test_helpers::{create_fake_image, test_metadata};
698 use crate::cache::{CacheArtifacts, CacheDir};
699 use std::fs;
700 use std::path::PathBuf;
701 use tempfile::TempDir;
702
703 #[test]
706 fn cache_initrd_compression_prefers_lz4_then_zstd_then_gzip() {
707 let all = "CONFIG_RD_GZIP=y\nCONFIG_RD_LZ4=y\nCONFIG_RD_ZSTD=y\n";
709 assert_eq!(initrd_compression_for_config(all), InitrdCompression::Lz4);
710 let al2023 = "CONFIG_RD_GZIP=y\n# CONFIG_RD_LZ4 is not set\nCONFIG_RD_ZSTD=y\n";
712 assert_eq!(
713 initrd_compression_for_config(al2023),
714 InitrdCompression::Zstd
715 );
716 let gzip_only = "CONFIG_RD_GZIP=y\n# CONFIG_RD_LZ4 is not set\n";
717 assert_eq!(
718 initrd_compression_for_config(gzip_only),
719 InitrdCompression::Gzip
720 );
721 assert_eq!(
723 initrd_compression_for_config("CONFIG_FOO=y\n"),
724 InitrdCompression::Uncompressed
725 );
726 assert_eq!(
728 initrd_compression_for_config("CONFIG_RD_LZ4_EXTRA=y\nCONFIG_RD_ZSTD=y\n"),
729 InitrdCompression::Zstd
730 );
731 }
732
733 #[test]
734 fn cache_initrd_compression_for_image_defaults_to_lz4() {
735 let tmp = TempDir::new().unwrap();
736 let image = tmp.path().join("bzImage");
737 fs::write(&image, b"fake").unwrap();
738 assert_eq!(initrd_compression_for_image(&image), InitrdCompression::Lz4);
740 fs::write(
742 tmp.path().join("config"),
743 "# CONFIG_RD_LZ4 is not set\nCONFIG_RD_ZSTD=y\n",
744 )
745 .unwrap();
746 assert_eq!(
747 initrd_compression_for_image(&image),
748 InitrdCompression::Zstd
749 );
750 }
751
752 #[test]
753 fn cached_kernel_config_uses_libbpf_guest_path() {
754 let tmp = TempDir::new().unwrap();
755 let image = tmp.path().join("bzImage");
756 let config = tmp.path().join("config");
757 fs::write(&image, b"fake image").unwrap();
758 fs::write(&config, b"CONFIG_PREEMPT_RCU=y\n").unwrap();
759 let metadata = test_metadata("7.0.0-14-generic");
760 fs::write(
761 tmp.path().join("metadata.json"),
762 serde_json::to_vec(&metadata).unwrap(),
763 )
764 .unwrap();
765
766 assert_eq!(
767 kernel_config_include_for_image(&image),
768 Some(("boot/config-7.0.0-14-generic".to_string(), config))
769 );
770 }
771
772 #[test]
773 fn cached_kernel_config_rejects_non_release_paths_and_mismatched_images() {
774 let tmp = TempDir::new().unwrap();
775 let image = tmp.path().join("bzImage");
776 fs::write(&image, b"fake image").unwrap();
777 fs::write(tmp.path().join("config"), b"CONFIG_PREEMPT_RCU=y\n").unwrap();
778
779 let invalid = test_metadata("../host-config");
780 fs::write(
781 tmp.path().join("metadata.json"),
782 serde_json::to_vec(&invalid).unwrap(),
783 )
784 .unwrap();
785 assert_eq!(kernel_config_include_for_image(&image), None);
786
787 let mut mismatch = test_metadata("7.0.0-test");
788 mismatch.image_name = "Image".to_string();
789 fs::write(
790 tmp.path().join("metadata.json"),
791 serde_json::to_vec(&mismatch).unwrap(),
792 )
793 .unwrap();
794 assert_eq!(kernel_config_include_for_image(&image), None);
795 }
796
797 #[test]
800 fn cache_metadata_serde_roundtrip() {
801 let meta = test_metadata("6.14.2");
802 let json = serde_json::to_string_pretty(&meta).unwrap();
803 let parsed: KernelMetadata = serde_json::from_str(&json).unwrap();
804 assert_eq!(parsed.version.as_deref(), Some("6.14.2"));
805 assert_eq!(parsed.source, KernelSource::Tarball);
806 assert_eq!(parsed.arch, "x86_64");
807 assert_eq!(parsed.image_name, "bzImage");
808 assert_eq!(parsed.config_hash.as_deref(), Some("abc123"));
809 assert_eq!(parsed.built_at, "2026-04-12T10:00:00Z");
810 assert_eq!(parsed.ktstr_kconfig_hash.as_deref(), Some("def456"));
811 assert!(!parsed.has_vmlinux);
812 assert!(!parsed.vmlinux_stripped);
813 }
814
815 #[test]
816 fn cache_metadata_serde_git_with_payload() {
817 let meta = KernelMetadata {
818 version: Some("6.15-rc3".to_string()),
819 source: KernelSource::git("a1b2c3d", "v6.15-rc3"),
820 arch: "aarch64".to_string(),
821 image_name: "Image".to_string(),
822 config_hash: None,
823 built_at: "2026-04-12T12:00:00Z".to_string(),
824 ktstr_kconfig_hash: None,
825 extra_kconfig_hash: None,
826 has_vmlinux: false,
827 vmlinux_stripped: false,
828 source_vmlinux_size: None,
829 source_vmlinux_mtime_secs: None,
830 };
831 let json = serde_json::to_string(&meta).unwrap();
832 let parsed: KernelMetadata = serde_json::from_str(&json).unwrap();
833 assert!(matches!(
834 parsed.source,
835 KernelSource::Git {
836 git_hash: Some(ref h),
837 git_ref: Some(ref r),
838 }
839 if h == "a1b2c3d" && r == "v6.15-rc3"
840 ));
841 }
842
843 #[test]
857 fn kernel_metadata_option_fields_serialize_as_explicit_null() {
858 let meta = KernelMetadata::new(
859 KernelSource::Tarball,
860 "x86_64",
861 "bzImage",
862 "2026-04-12T10:00:00Z",
863 );
864 let json = serde_json::to_string(&meta).unwrap();
865 for null_key in [
866 r#""version":null"#,
867 r#""config_hash":null"#,
868 r#""ktstr_kconfig_hash":null"#,
869 r#""extra_kconfig_hash":null"#,
870 r#""source_vmlinux_size":null"#,
871 r#""source_vmlinux_mtime_secs":null"#,
872 ] {
873 assert!(
874 json.contains(null_key),
875 "serialized JSON must contain explicit `{null_key}` \
876 — None must round-trip as null, not as an absent \
877 key. Got: {json}",
878 );
879 }
880 let parsed: KernelMetadata = serde_json::from_str(&json).unwrap();
882 assert!(parsed.version.is_none(), "version must round-trip None");
883 assert!(
884 parsed.config_hash.is_none(),
885 "config_hash must round-trip None"
886 );
887 assert!(
888 parsed.ktstr_kconfig_hash.is_none(),
889 "ktstr_kconfig_hash must round-trip None"
890 );
891 assert!(
892 parsed.extra_kconfig_hash.is_none(),
893 "extra_kconfig_hash must round-trip None"
894 );
895 assert!(
896 parsed.source_vmlinux_size.is_none(),
897 "source_vmlinux_size must round-trip None"
898 );
899 assert!(
900 parsed.source_vmlinux_mtime_secs.is_none(),
901 "source_vmlinux_mtime_secs must round-trip None"
902 );
903 }
904
905 #[test]
918 fn kernel_metadata_all_option_fields_populated_roundtrip() {
919 let meta = KernelMetadata::new(
920 KernelSource::Tarball,
921 "x86_64",
922 "bzImage",
923 "2026-04-12T10:00:00Z",
924 )
925 .with_version("6.14.2")
926 .with_config_hash("cfg-hash")
927 .with_ktstr_kconfig_hash("ktstr-hash")
928 .with_extra_kconfig_hash("extra-hash")
929 .with_source_vmlinux_stat(123_456_789, 1_700_000_000);
930 let json = serde_json::to_string(&meta).unwrap();
931 let parsed: KernelMetadata = serde_json::from_str(&json).unwrap();
932 assert_eq!(parsed.version.as_deref(), Some("6.14.2"));
933 assert_eq!(parsed.config_hash.as_deref(), Some("cfg-hash"));
934 assert_eq!(parsed.ktstr_kconfig_hash.as_deref(), Some("ktstr-hash"));
935 assert_eq!(parsed.extra_kconfig_hash.as_deref(), Some("extra-hash"));
936 assert_eq!(parsed.source_vmlinux_size, Some(123_456_789));
937 assert_eq!(parsed.source_vmlinux_mtime_secs, Some(1_700_000_000));
938 }
939
940 #[test]
947 fn kernel_metadata_clear_setters_round_trip() {
948 let populated = KernelMetadata::new(
949 KernelSource::Tarball,
950 "x86_64",
951 "bzImage",
952 "2026-04-12T10:00:00Z",
953 )
954 .with_version("6.14.2")
955 .with_config_hash("cfg-hash")
956 .with_ktstr_kconfig_hash("ktstr-hash")
957 .with_extra_kconfig_hash("extra-hash")
958 .with_source_vmlinux_stat(123_456_789, 1_700_000_000);
959 assert!(populated.version.is_some());
960 assert!(populated.config_hash.is_some());
961 assert!(populated.ktstr_kconfig_hash.is_some());
962 assert!(populated.extra_kconfig_hash.is_some());
963 assert!(populated.source_vmlinux_size.is_some());
964 assert!(populated.source_vmlinux_mtime_secs.is_some());
965
966 let cleared = populated
967 .clear_version()
968 .clear_config_hash()
969 .clear_ktstr_kconfig_hash()
970 .clear_extra_kconfig_hash()
971 .clear_source_vmlinux_stat();
972 assert!(cleared.version.is_none());
973 assert!(cleared.config_hash.is_none());
974 assert!(cleared.ktstr_kconfig_hash.is_none());
975 assert!(cleared.extra_kconfig_hash.is_none());
976 assert!(cleared.source_vmlinux_size.is_none());
977 assert!(cleared.source_vmlinux_mtime_secs.is_none());
978 }
979
980 #[test]
981 fn cache_metadata_serde_local_with_source_tree() {
982 let meta = KernelMetadata {
983 version: Some("6.14.0".to_string()),
984 source: KernelSource::Local {
985 source_tree_path: Some(PathBuf::from("/tmp/linux")),
986 git_hash: Some("deadbee".to_string()),
987 },
988 arch: "x86_64".to_string(),
989 image_name: "bzImage".to_string(),
990 config_hash: Some("fff000".to_string()),
991 built_at: "2026-04-12T14:00:00Z".to_string(),
992 ktstr_kconfig_hash: Some("aaa111".to_string()),
993 extra_kconfig_hash: None,
994 has_vmlinux: true,
995 vmlinux_stripped: true,
996 source_vmlinux_size: None,
997 source_vmlinux_mtime_secs: None,
998 };
999 let json = serde_json::to_string(&meta).unwrap();
1000 let parsed: KernelMetadata = serde_json::from_str(&json).unwrap();
1001 assert!(matches!(
1002 parsed.source,
1003 KernelSource::Local {
1004 source_tree_path: Some(ref p),
1005 git_hash: Some(ref h),
1006 }
1007 if p == &PathBuf::from("/tmp/linux") && h == "deadbee"
1008 ));
1009 assert!(parsed.has_vmlinux);
1010 assert!(parsed.vmlinux_stripped);
1011 }
1012
1013 #[test]
1022 fn kernel_source_local_git_hash_serde_round_trip_none() {
1023 let src = KernelSource::Local {
1024 source_tree_path: Some(PathBuf::from("/tmp/linux")),
1025 git_hash: None,
1026 };
1027 let json = serde_json::to_string(&src).unwrap();
1028 assert!(
1029 json.contains(r#""git_hash":null"#),
1030 "git_hash=None must round-trip as explicit null, got {json}"
1031 );
1032 let parsed: KernelSource = serde_json::from_str(&json).unwrap();
1033 assert!(matches!(parsed, KernelSource::Local { git_hash: None, .. }));
1034 }
1035
1036 #[test]
1040 fn kernel_source_option_fields_serialize_as_explicit_null() {
1041 let local = KernelSource::Local {
1042 source_tree_path: None,
1043 git_hash: None,
1044 };
1045 let local_json = serde_json::to_string(&local).unwrap();
1046 assert!(
1047 local_json.contains(r#""source_tree_path":null"#),
1048 "Local.source_tree_path=None must serialize as explicit null, got {local_json}"
1049 );
1050 assert!(
1051 local_json.contains(r#""git_hash":null"#),
1052 "Local.git_hash=None must serialize as explicit null, got {local_json}"
1053 );
1054
1055 let git = KernelSource::Git {
1056 git_hash: None,
1057 git_ref: None,
1058 };
1059 let git_json = serde_json::to_string(&git).unwrap();
1060 assert!(
1061 git_json.contains(r#""git_hash":null"#),
1062 "Git.git_hash=None must serialize as explicit null, got {git_json}"
1063 );
1064 assert!(
1065 git_json.contains(r#""ref":null"#),
1066 "Git.git_ref=None must serialize as explicit null under the `ref` key, got {git_json}"
1067 );
1068 }
1069
1070 #[test]
1073 fn kernel_source_absent_option_keys_deserialize_as_none() {
1074 let git_bare: KernelSource = serde_json::from_str(r#"{"type":"git"}"#)
1075 .expect("Git with absent Option keys must deserialize");
1076 assert!(matches!(
1077 git_bare,
1078 KernelSource::Git {
1079 git_hash: None,
1080 git_ref: None,
1081 }
1082 ));
1083
1084 let git_hash_only: KernelSource =
1085 serde_json::from_str(r#"{"type":"git","git_hash":"abc"}"#)
1086 .expect("Git with only git_hash must deserialize");
1087 assert!(matches!(
1088 git_hash_only,
1089 KernelSource::Git {
1090 git_hash: Some(ref h),
1091 git_ref: None,
1092 } if h == "abc"
1093 ));
1094
1095 let git_ref_only: KernelSource = serde_json::from_str(r#"{"type":"git","ref":"main"}"#)
1096 .expect("Git with only ref must deserialize");
1097 assert!(matches!(
1098 git_ref_only,
1099 KernelSource::Git {
1100 git_hash: None,
1101 git_ref: Some(ref r),
1102 } if r == "main"
1103 ));
1104
1105 let local_bare: KernelSource = serde_json::from_str(r#"{"type":"local"}"#)
1106 .expect("Local with absent Option keys must deserialize");
1107 assert!(matches!(
1108 local_bare,
1109 KernelSource::Local {
1110 source_tree_path: None,
1111 git_hash: None,
1112 }
1113 ));
1114
1115 let local_path_only: KernelSource =
1116 serde_json::from_str(r#"{"type":"local","source_tree_path":"/tmp/linux"}"#)
1117 .expect("Local with only source_tree_path must deserialize");
1118 assert!(matches!(
1119 local_path_only,
1120 KernelSource::Local {
1121 source_tree_path: Some(ref p),
1122 git_hash: None,
1123 } if p.to_str() == Some("/tmp/linux")
1124 ));
1125
1126 let local_hash_only: KernelSource =
1127 serde_json::from_str(r#"{"type":"local","git_hash":"deadbeef"}"#)
1128 .expect("Local with only git_hash must deserialize");
1129 assert!(matches!(
1130 local_hash_only,
1131 KernelSource::Local {
1132 source_tree_path: None,
1133 git_hash: Some(ref h),
1134 } if h == "deadbeef"
1135 ));
1136 }
1137
1138 #[test]
1139 fn kernel_source_serde_tagged_representation() {
1140 let t = serde_json::to_string(&KernelSource::Tarball).unwrap();
1141 assert_eq!(t, r#"{"type":"tarball"}"#);
1142 let g = serde_json::to_string(&KernelSource::git("abc", "main")).unwrap();
1143 assert!(g.contains(r#""type":"git""#));
1144 assert!(g.contains(r#""git_hash":"abc""#));
1145 assert!(g.contains(r#""ref":"main""#));
1146 let l = serde_json::to_string(&KernelSource::Local {
1147 source_tree_path: Some(PathBuf::from("/tmp/linux")),
1148 git_hash: Some("a1b2c3d".to_string()),
1149 })
1150 .unwrap();
1151 assert!(l.contains(r#""type":"local""#));
1152 assert!(l.contains(r#""source_tree_path":"/tmp/linux""#));
1153 assert!(l.contains(r#""git_hash":"a1b2c3d""#));
1154 }
1155
1156 #[test]
1158 fn classify_corrupt_reason_covers_every_documented_prefix() {
1159 let cases: &[(&str, &str)] = &[
1160 ("metadata.json missing", "missing"),
1161 (
1162 "metadata.json unreadable: Is a directory (os error 21)",
1163 "unreadable",
1164 ),
1165 (
1166 "metadata.json schema drift: missing field `source` at line 1 column 21",
1167 "schema_drift",
1168 ),
1169 (
1170 "metadata.json malformed: expected value at line 1 column 1",
1171 "malformed",
1172 ),
1173 (
1174 "metadata.json truncated: EOF while parsing a value at line 1 column 10",
1175 "truncated",
1176 ),
1177 (
1178 "metadata.json parse error: something unexpected",
1179 "parse_error",
1180 ),
1181 (
1182 "image file bzImage missing from entry directory",
1183 "image_missing",
1184 ),
1185 ("some future prefix nobody wrote yet", "unknown"),
1186 ];
1187 for (reason, expected) in cases {
1188 assert_eq!(
1189 classify_corrupt_reason(reason),
1190 *expected,
1191 "reason `{reason}` should classify as `{expected}`",
1192 );
1193 }
1194 }
1195
1196 #[test]
1203 fn classify_corrupt_reason_image_missing_requires_exact_suffix() {
1204 assert_eq!(
1209 classify_corrupt_reason("image file bzImage missing checksum field"),
1210 "unknown",
1211 "non-canonical 'image file … missing X' reason must NOT \
1212 classify as `image_missing` — only the exact \
1213 format_image_missing_reason() form is accepted",
1214 );
1215 assert_eq!(
1217 classify_corrupt_reason("foo bzImage missing from entry directory"),
1218 "unknown",
1219 "suffix-only match without the canonical prefix must classify as unknown",
1220 );
1221 assert_eq!(
1225 classify_corrupt_reason("image file missing from entry directory"),
1226 "unknown",
1227 "prefix+suffix with no image_name in between must classify as unknown",
1228 );
1229 }
1230
1231 #[test]
1236 fn classify_corrupt_reason_accepts_every_format_image_missing_output() {
1237 for image_name in [
1238 "bzImage",
1239 "Image",
1240 "vmlinuz-6.14.2",
1241 "kernel.bin",
1242 "image_with_underscores",
1243 "name-with-many-dashes",
1244 ] {
1245 let reason = format_image_missing_reason(image_name);
1246 assert_eq!(
1247 classify_corrupt_reason(&reason),
1248 "image_missing",
1249 "every produced reason (image_name={image_name:?}) must \
1250 classify as image_missing — got reason {reason:?}",
1251 );
1252 }
1253 }
1254
1255 #[test]
1258 fn listed_entry_error_kind_dispatches_on_variant() {
1259 let tmp = TempDir::new().unwrap();
1260 let cache = CacheDir::with_root(tmp.path().join("cache"));
1261 let src_dir = TempDir::new().unwrap();
1262 let image = create_fake_image(src_dir.path());
1263 let meta = test_metadata("6.14.2");
1264 cache
1265 .store("valid-ek", &CacheArtifacts::new(&image), &meta)
1266 .unwrap();
1267
1268 let bad_dir = tmp.path().join("cache").join("corrupt-ek");
1269 fs::create_dir_all(&bad_dir).unwrap();
1270
1271 let entries = cache.list().unwrap();
1272 assert_eq!(entries.len(), 2);
1273 let valid = entries
1274 .iter()
1275 .find(|e| e.key() == "valid-ek")
1276 .expect("valid entry must be listed");
1277 let corrupt = entries
1278 .iter()
1279 .find(|e| e.key() == "corrupt-ek")
1280 .expect("corrupt entry must be listed");
1281 assert_eq!(
1282 valid.error_kind(),
1283 None,
1284 "Valid entries must report no error_kind",
1285 );
1286 assert_eq!(
1287 corrupt.error_kind(),
1288 Some("missing"),
1289 "missing-metadata Corrupt entry must classify as `missing`",
1290 );
1291 }
1292
1293 #[test]
1301 fn kconfig_status_display_matches_renders_lowercase_word() {
1302 assert_eq!(KconfigStatus::Matches.to_string(), "matches");
1303 }
1304
1305 #[test]
1306 fn kconfig_status_display_stale_renders_lowercase_word_without_hashes() {
1307 let s = KconfigStatus::Stale {
1308 cached: "deadbeef".to_string(),
1309 current: "cafebabe".to_string(),
1310 }
1311 .to_string();
1312 assert_eq!(
1313 s, "stale",
1314 "Display elides the cached/current hashes; callers that need them must match on the variant directly"
1315 );
1316 }
1317
1318 #[test]
1319 fn kconfig_status_display_untracked_renders_lowercase_word() {
1320 assert_eq!(KconfigStatus::Untracked.to_string(), "untracked");
1321 }
1322
1323 #[test]
1336 fn kconfig_status_matches_is_neither_stale_nor_untracked() {
1337 let s = KconfigStatus::Matches;
1338 assert!(!s.is_stale(), "Matches must not be stale");
1339 assert!(!s.is_untracked(), "Matches must not be untracked");
1340 }
1341
1342 #[test]
1345 fn kconfig_status_stale_is_stale_only() {
1346 let s = KconfigStatus::Stale {
1347 cached: "old".to_string(),
1348 current: "new".to_string(),
1349 };
1350 assert!(s.is_stale(), "Stale variant must report is_stale=true");
1351 assert!(
1352 !s.is_untracked(),
1353 "Stale must NOT report is_untracked — the two predicates \
1354 discriminate distinct variants",
1355 );
1356 }
1357
1358 #[test]
1361 fn kconfig_status_untracked_is_untracked_only() {
1362 let s = KconfigStatus::Untracked;
1363 assert!(
1364 s.is_untracked(),
1365 "Untracked variant must report is_untracked=true"
1366 );
1367 assert!(
1368 !s.is_stale(),
1369 "Untracked must NOT report is_stale — pre-tracking-format \
1370 entries are unknown, not stale; treating them as stale \
1371 would force a rebuild on every old cache hit",
1372 );
1373 }
1374
1375 #[test]
1392 fn as_local_git_hash_returns_local_hash() {
1393 let src = KernelSource::Local {
1394 source_tree_path: Some(PathBuf::from("/tmp/linux")),
1395 git_hash: Some("deadbee".to_string()),
1396 };
1397 assert_eq!(
1398 src.as_local_git_hash(),
1399 Some("deadbee"),
1400 "Local with git_hash=Some must surface the inner str",
1401 );
1402 }
1403
1404 #[test]
1409 fn as_local_git_hash_returns_none_when_local_has_no_hash() {
1410 let src = KernelSource::Local {
1411 source_tree_path: Some(PathBuf::from("/tmp/linux")),
1412 git_hash: None,
1413 };
1414 assert_eq!(
1415 src.as_local_git_hash(),
1416 None,
1417 "Local with git_hash=None must surface None — the dirty \
1418 check has no anchor on a non-git or dirty tree",
1419 );
1420 }
1421
1422 #[test]
1428 fn as_local_git_hash_returns_none_for_tarball() {
1429 let src = KernelSource::Tarball;
1430 assert_eq!(
1431 src.as_local_git_hash(),
1432 None,
1433 "Tarball variant has no git_hash and must surface None",
1434 );
1435 }
1436
1437 #[test]
1444 fn as_local_git_hash_returns_none_for_git_even_with_hash_field() {
1445 let src = KernelSource::git("a1b2c3d", "main");
1446 assert_eq!(
1447 src.as_local_git_hash(),
1448 None,
1449 "Git variant has its own git_hash field but the \
1450 accessor is named as_LOCAL_git_hash — it MUST NOT \
1451 surface the Git variant's hash, since the Git hash \
1452 describes the cloned commit (acquire-time) and the \
1453 Local hash describes the operator's working tree HEAD \
1454 (a different role with different semantics)",
1455 );
1456 }
1457
1458 #[test]
1469 fn format_image_missing_reason_uses_canonical_prefix_and_suffix() {
1470 let reason = format_image_missing_reason("bzImage");
1471 assert_eq!(
1472 reason, "image file bzImage missing from entry directory",
1473 "the produced reason MUST be the exact prefix + image_name + \
1474 suffix concatenation — any drift breaks the classifier's \
1475 exact-match predicate",
1476 );
1477 assert!(
1478 reason.starts_with(IMAGE_MISSING_PREFIX),
1479 "produced reason must start with IMAGE_MISSING_PREFIX",
1480 );
1481 assert!(
1482 reason.ends_with(IMAGE_MISSING_SUFFIX),
1483 "produced reason must end with IMAGE_MISSING_SUFFIX",
1484 );
1485 }
1486
1487 #[test]
1498 fn format_image_missing_reason_with_empty_image_name() {
1499 let reason = format_image_missing_reason("");
1500 assert_eq!(
1501 reason, "image file missing from entry directory",
1502 "empty image_name must produce a verbatim concatenation \
1503 (prefix trailing-space + suffix leading-space → two \
1504 consecutive spaces between `file` and `missing`); the \
1505 producer does not validate (validation is at \
1506 validate_filename time), so the degenerate concatenation \
1507 is the documented behaviour",
1508 );
1509 assert_eq!(
1513 classify_corrupt_reason(&reason),
1514 "unknown",
1515 "the classifier's length-guard MUST reject the \
1516 prefix+suffix-with-empty-image-name form — a regression \
1517 that loosened the guard would let a future bug emit \
1518 format_image_missing_reason(\"\") and silently classify \
1519 it as image_missing, hiding the real defect (empty \
1520 image_name in metadata)",
1521 );
1522 }
1523
1524 #[test]
1534 fn cache_entry_disk_template_path_joins_canonical_filename() {
1535 let tmp = TempDir::new().unwrap();
1536 let cache = CacheDir::with_root(tmp.path().join("cache"));
1537 let src_dir = TempDir::new().unwrap();
1538 let image = create_fake_image(src_dir.path());
1539 let entry = cache
1540 .store(
1541 "disk-tmpl-key",
1542 &CacheArtifacts::new(&image),
1543 &test_metadata("6.14.2"),
1544 )
1545 .unwrap();
1546 assert_eq!(
1547 entry.disk_template_path(),
1548 entry.path.join("disk-template.img"),
1549 "disk_template_path() MUST resolve to <entry>/disk-template.img — \
1550 the literal `disk-template.img` is the canonical filename the \
1551 VMM disk_template module writes/reads",
1552 );
1553 assert!(
1559 !entry.disk_template_path().exists(),
1560 "disk_template_path() must be path-only — store() does not \
1561 create the file; absence is the expected post-store state",
1562 );
1563 }
1564
1565 #[test]
1575 fn cache_entry_has_extra_kconfig_true_when_hash_present() {
1576 let tmp = TempDir::new().unwrap();
1577 let cache = CacheDir::with_root(tmp.path().join("cache"));
1578 let src_dir = TempDir::new().unwrap();
1579 let image = create_fake_image(src_dir.path());
1580 let meta = test_metadata("6.14.2").with_extra_kconfig_hash("user-fragment-hash");
1581 let entry = cache
1582 .store("with-extra", &CacheArtifacts::new(&image), &meta)
1583 .unwrap();
1584 assert!(
1585 entry.has_extra_kconfig(),
1586 "extra_kconfig_hash=Some MUST report has_extra_kconfig()=true — \
1587 a regression that flipped polarity would invert the \
1588 rebuild-on-fragment-change policy",
1589 );
1590 }
1591
1592 #[test]
1594 fn cache_entry_has_extra_kconfig_false_when_hash_absent() {
1595 let tmp = TempDir::new().unwrap();
1596 let cache = CacheDir::with_root(tmp.path().join("cache"));
1597 let src_dir = TempDir::new().unwrap();
1598 let image = create_fake_image(src_dir.path());
1599 let meta = test_metadata("6.14.2");
1601 assert!(
1602 meta.extra_kconfig_hash.is_none(),
1603 "test_metadata default must keep extra_kconfig_hash=None \
1604 so this test exercises the false branch",
1605 );
1606 let entry = cache
1607 .store("no-extra", &CacheArtifacts::new(&image), &meta)
1608 .unwrap();
1609 assert!(
1610 !entry.has_extra_kconfig(),
1611 "extra_kconfig_hash=None MUST report has_extra_kconfig()=false",
1612 );
1613 }
1614
1615 #[test]
1625 fn listed_entry_path_accessor_returns_valid_entry_path() {
1626 let tmp = TempDir::new().unwrap();
1627 let cache = CacheDir::with_root(tmp.path().join("cache"));
1628 let src_dir = TempDir::new().unwrap();
1629 let image = create_fake_image(src_dir.path());
1630 let entry = cache
1631 .store(
1632 "valid-path-test",
1633 &CacheArtifacts::new(&image),
1634 &test_metadata("6.14.2"),
1635 )
1636 .unwrap();
1637 let expected_path = entry.path.clone();
1638 let entries = cache.list().unwrap();
1639 let listed = entries
1640 .iter()
1641 .find(|e| e.key() == "valid-path-test")
1642 .expect("the just-stored entry must be in the list");
1643 assert!(
1644 matches!(listed, ListedEntry::Valid(_)),
1645 "precondition: stored entry must surface as Valid",
1646 );
1647 assert_eq!(
1648 listed.path(),
1649 expected_path,
1650 "ListedEntry::path() on Valid must return the inner \
1651 CacheEntry's path — accessor MUST forward, not synthesize",
1652 );
1653 }
1654
1655 #[test]
1657 fn listed_entry_path_accessor_returns_corrupt_entry_path() {
1658 let tmp = TempDir::new().unwrap();
1659 let cache = CacheDir::with_root(tmp.path().join("cache"));
1660 let entry_dir = tmp.path().join("cache").join("corrupt-path-test");
1663 std::fs::create_dir_all(&entry_dir).unwrap();
1664 let entries = cache.list().unwrap();
1665 let listed = entries
1666 .iter()
1667 .find(|e| e.key() == "corrupt-path-test")
1668 .expect("corrupt-shaped entry must be in the list");
1669 assert!(
1670 matches!(listed, ListedEntry::Corrupt { .. }),
1671 "precondition: missing-metadata entry must surface as Corrupt",
1672 );
1673 assert_eq!(
1674 listed.path(),
1675 entry_dir,
1676 "ListedEntry::path() on Corrupt must return the variant's \
1677 `path` field — accessor MUST forward, not synthesize",
1678 );
1679 }
1680}