-
Notifications
You must be signed in to change notification settings - Fork 86
/
store.rs
1895 lines (1762 loc) · 71.6 KB
/
store.rs
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! APIs for storing (layered) container images as OSTree commits
//!
//! # Extension of encapsulation support
//!
//! This code supports ingesting arbitrary layered container images from an ostree-exported
//! base. See [`encapsulate`][`super::encapsulate()`] for more information on encaspulation of images.
use super::*;
use crate::chunking::{self, Chunk};
use crate::logging::system_repo_journal_print;
use crate::refescape;
use crate::sysroot::SysrootLock;
use crate::utils::ResultExt;
use anyhow::{anyhow, Context};
use camino::{Utf8Path, Utf8PathBuf};
use cap_std_ext::cap_std;
use cap_std_ext::cap_std::fs::{Dir, MetadataExt};
use cap_std_ext::cmdext::CapStdExtCommandExt;
use containers_image_proxy::{ImageProxy, OpenedImage};
use flate2::Compression;
use fn_error_context::context;
use futures_util::TryFutureExt;
use oci_spec::image::{
self as oci_image, Arch, Descriptor, Digest, History, ImageConfiguration, ImageManifest,
};
use ostree::prelude::{Cast, FileEnumeratorExt, FileExt, ToVariant};
use ostree::{gio, glib};
use std::collections::{BTreeSet, HashMap};
use std::iter::FromIterator;
use tokio::sync::mpsc::{Receiver, Sender};
/// Configuration for the proxy.
///
/// We re-export this rather than inventing our own wrapper
/// in the interest of avoiding duplication.
pub use containers_image_proxy::ImageProxyConfig;
/// The ostree ref prefix for blobs.
const LAYER_PREFIX: &str = "ostree/container/blob";
/// The ostree ref prefix for image references.
const IMAGE_PREFIX: &str = "ostree/container/image";
/// The ostree ref prefix for "base" image references that are used by derived images.
/// If you maintain tooling which is locally building derived commits, write a ref
/// with this prefix that is owned by your code. It's a best practice to prefix the
/// ref with the project name, so the final ref may be of the form e.g. `ostree/container/baseimage/bootc/foo`.
pub const BASE_IMAGE_PREFIX: &str = "ostree/container/baseimage";
/// The key injected into the merge commit for the manifest digest.
pub(crate) const META_MANIFEST_DIGEST: &str = "ostree.manifest-digest";
/// The key injected into the merge commit with the manifest serialized as JSON.
const META_MANIFEST: &str = "ostree.manifest";
/// The key injected into the merge commit with the image configuration serialized as JSON.
const META_CONFIG: &str = "ostree.container.image-config";
/// Value of type `a{sa{su}}` containing number of filtered out files
pub const META_FILTERED: &str = "ostree.tar-filtered";
/// The type used to store content filtering information with `META_FILTERED`.
pub type MetaFilteredData = HashMap<String, HashMap<String, u32>>;
/// The ref prefixes which point to ostree deployments. (TODO: Add an official API for this)
const OSTREE_BASE_DEPLOYMENT_REFS: &[&str] = &["ostree/0", "ostree/1"];
/// A layering violation we'll carry for a bit to band-aid over https://github.com/coreos/rpm-ostree/issues/4185
const RPMOSTREE_BASE_REFS: &[&str] = &["rpmostree/base"];
/// Convert e.g. sha256:12345... into `/ostree/container/blob/sha256_2B12345...`.
fn ref_for_blob_digest(d: &str) -> Result<String> {
refescape::prefix_escape_for_ref(LAYER_PREFIX, d)
}
/// Convert e.g. sha256:12345... into `/ostree/container/blob/sha256_2B12345...`.
fn ref_for_layer(l: &oci_image::Descriptor) -> Result<String> {
ref_for_blob_digest(&l.digest().as_ref())
}
/// Convert e.g. sha256:12345... into `/ostree/container/blob/sha256_2B12345...`.
fn ref_for_image(l: &ImageReference) -> Result<String> {
refescape::prefix_escape_for_ref(IMAGE_PREFIX, &l.to_string())
}
/// Sent across a channel to track start and end of a container fetch.
#[derive(Debug)]
pub enum ImportProgress {
/// Started fetching this layer.
OstreeChunkStarted(Descriptor),
/// Successfully completed the fetch of this layer.
OstreeChunkCompleted(Descriptor),
/// Started fetching this layer.
DerivedLayerStarted(Descriptor),
/// Successfully completed the fetch of this layer.
DerivedLayerCompleted(Descriptor),
}
impl ImportProgress {
/// Returns `true` if this message signifies the start of a new layer being fetched.
pub fn is_starting(&self) -> bool {
match self {
ImportProgress::OstreeChunkStarted(_) => true,
ImportProgress::OstreeChunkCompleted(_) => false,
ImportProgress::DerivedLayerStarted(_) => true,
ImportProgress::DerivedLayerCompleted(_) => false,
}
}
}
/// Sent across a channel to track the byte-level progress of a layer fetch.
#[derive(Debug)]
pub struct LayerProgress {
/// Index of the layer in the manifest
pub layer_index: usize,
/// Number of bytes downloaded
pub fetched: u64,
/// Total number of bytes outstanding
pub total: u64,
}
/// State of an already pulled layered image.
#[derive(Debug, PartialEq, Eq)]
pub struct LayeredImageState {
/// The base ostree commit
pub base_commit: String,
/// The merge commit unions all layers
pub merge_commit: String,
/// The digest of the original manifest
pub manifest_digest: Digest,
/// The image manfiest
pub manifest: ImageManifest,
/// The image configuration
pub configuration: ImageConfiguration,
/// Metadata for (cached, previously fetched) updates to the image, if any.
pub cached_update: Option<CachedImageUpdate>,
}
impl LayeredImageState {
/// Return the merged ostree commit for this image.
///
/// This is not the same as the underlying base ostree commit.
pub fn get_commit(&self) -> &str {
self.merge_commit.as_str()
}
/// Retrieve the container image version.
pub fn version(&self) -> Option<&str> {
super::version_for_config(&self.configuration)
}
}
/// Locally cached metadata for an update to an existing image.
#[derive(Debug, PartialEq, Eq)]
pub struct CachedImageUpdate {
/// The image manifest
pub manifest: ImageManifest,
/// The image configuration
pub config: ImageConfiguration,
/// The digest of the manifest
pub manifest_digest: Digest,
}
impl CachedImageUpdate {
/// Retrieve the container image version.
pub fn version(&self) -> Option<&str> {
super::version_for_config(&self.config)
}
}
/// Context for importing a container image.
#[derive(Debug)]
pub struct ImageImporter {
repo: ostree::Repo,
pub(crate) proxy: ImageProxy,
imgref: OstreeImageReference,
target_imgref: Option<OstreeImageReference>,
no_imgref: bool, // If true, do not write final image ref
disable_gc: bool, // If true, don't prune unused image layers
/// If true, require the image has the bootable flag
require_bootable: bool,
/// If true, we have ostree v2024.3 or newer.
ostree_v2024_3: bool,
pub(crate) proxy_img: OpenedImage,
layer_progress: Option<Sender<ImportProgress>>,
layer_byte_progress: Option<tokio::sync::watch::Sender<Option<LayerProgress>>>,
}
/// Result of invoking [`ImageImporter::prepare`].
#[derive(Debug)]
pub enum PrepareResult {
/// The image reference is already present; the contained string is the OSTree commit.
AlreadyPresent(Box<LayeredImageState>),
/// The image needs to be downloaded
Ready(Box<PreparedImport>),
}
/// A container image layer with associated downloaded-or-not state.
#[derive(Debug)]
pub struct ManifestLayerState {
/// The underlying layer descriptor.
pub(crate) layer: oci_image::Descriptor,
// TODO semver: Make this readonly via an accessor
/// The ostree ref name for this layer.
pub ostree_ref: String,
// TODO semver: Make this readonly via an accessor
/// The ostree commit that caches this layer, if present.
pub commit: Option<String>,
}
impl ManifestLayerState {
/// Return the layer descriptor.
pub fn layer(&self) -> &oci_image::Descriptor {
&self.layer
}
}
/// Information about which layers need to be downloaded.
#[derive(Debug)]
pub struct PreparedImport {
/// The manifest digest that was found
pub manifest_digest: Digest,
/// The deserialized manifest.
pub manifest: oci_image::ImageManifest,
/// The deserialized configuration.
pub config: oci_image::ImageConfiguration,
/// The previous manifest
pub previous_state: Option<Box<LayeredImageState>>,
/// The previously stored manifest digest.
pub previous_manifest_digest: Option<Digest>,
/// The previously stored image ID.
pub previous_imageid: Option<String>,
/// The layers containing split objects
pub ostree_layers: Vec<ManifestLayerState>,
/// The layer for the ostree commit.
pub ostree_commit_layer: Option<ManifestLayerState>,
/// Any further non-ostree (derived) layers.
pub layers: Vec<ManifestLayerState>,
}
impl PreparedImport {
/// Iterate over all layers; the commit layer, the ostree split object layers, and any non-ostree layers.
pub fn all_layers(&self) -> impl Iterator<Item = &ManifestLayerState> {
self.ostree_commit_layer
.iter()
.chain(self.ostree_layers.iter())
.chain(self.layers.iter())
}
/// Retrieve the container image version.
pub fn version(&self) -> Option<&str> {
super::version_for_config(&self.config)
}
/// If this image is using any deprecated features, return a message saying so.
pub fn deprecated_warning(&self) -> Option<&'static str> {
None
}
/// Iterate over all layers paired with their history entry.
/// An error will be returned if the history does not cover all entries.
pub fn layers_with_history(
&self,
) -> impl Iterator<Item = Result<(&ManifestLayerState, &History)>> {
// FIXME use .filter(|h| h.empty_layer.unwrap_or_default()) after https://github.com/containers/oci-spec-rs/pull/100 lands.
let truncated = std::iter::once_with(|| Err(anyhow::anyhow!("Truncated history")));
let history = self.config.history().iter().map(Ok).chain(truncated);
self.all_layers()
.zip(history)
.map(|(s, h)| h.map(|h| (s, h)))
}
/// Iterate over all layers that are not present, along with their history description.
pub fn layers_to_fetch(&self) -> impl Iterator<Item = Result<(&ManifestLayerState, &str)>> {
self.layers_with_history().filter_map(|r| {
r.map(|(l, h)| {
l.commit.is_none().then(|| {
let comment = h.created_by().as_deref().unwrap_or("");
(l, comment)
})
})
.transpose()
})
}
/// Common helper to format a string for the status
pub(crate) fn format_layer_status(&self) -> Option<String> {
let (stored, to_fetch, to_fetch_size) =
self.all_layers()
.fold((0u32, 0u32, 0u64), |(stored, to_fetch, sz), v| {
if v.commit.is_some() {
(stored + 1, to_fetch, sz)
} else {
(stored, to_fetch + 1, sz + v.layer().size())
}
});
(to_fetch > 0).then(|| {
let size = crate::glib::format_size(to_fetch_size);
format!("layers already present: {stored}; layers needed: {to_fetch} ({size})")
})
}
}
// Given a manifest, compute its ostree ref name and cached ostree commit
pub(crate) fn query_layer(
repo: &ostree::Repo,
layer: oci_image::Descriptor,
) -> Result<ManifestLayerState> {
let ostree_ref = ref_for_layer(&layer)?;
let commit = repo.resolve_rev(&ostree_ref, true)?.map(|s| s.to_string());
Ok(ManifestLayerState {
layer,
ostree_ref,
commit,
})
}
#[context("Reading manifest data from commit")]
fn manifest_data_from_commitmeta(
commit_meta: &glib::VariantDict,
) -> Result<(oci_image::ImageManifest, Digest)> {
let digest = commit_meta
.lookup::<String>(META_MANIFEST_DIGEST)?
.ok_or_else(|| anyhow!("Missing {} metadata on merge commit", META_MANIFEST_DIGEST))?;
let digest = Digest::from_str(&digest)?;
let manifest_bytes: String = commit_meta
.lookup::<String>(META_MANIFEST)?
.ok_or_else(|| anyhow!("Failed to find {} metadata key", META_MANIFEST))?;
let r = serde_json::from_str(&manifest_bytes)?;
Ok((r, digest))
}
fn image_config_from_commitmeta(commit_meta: &glib::VariantDict) -> Result<ImageConfiguration> {
let config = if let Some(config) = commit_meta
.lookup::<String>(META_CONFIG)?
.filter(|v| v != "null") // Format v0 apparently old versions injected `null` here sadly...
.map(|v| serde_json::from_str(&v).map_err(anyhow::Error::msg))
.transpose()?
{
config
} else {
tracing::debug!("No image configuration found");
Default::default()
};
Ok(config)
}
/// Return the original digest of the manifest stored in the commit metadata.
/// This will be a string of the form e.g. `sha256:<digest>`.
///
/// This can be used to uniquely identify the image. For example, it can be used
/// in a "digested pull spec" like `quay.io/someuser/exampleos@sha256:...`.
pub fn manifest_digest_from_commit(commit: &glib::Variant) -> Result<Digest> {
let commit_meta = &commit.child_value(0);
let commit_meta = &glib::VariantDict::new(Some(commit_meta));
Ok(manifest_data_from_commitmeta(commit_meta)?.1)
}
/// Given a target diffid, return its corresponding layer. In our current model,
/// we require a 1-to-1 mapping between the two up until the ostree level.
/// For a bit more information on this, see https://github.com/opencontainers/image-spec/blob/main/config.md
fn layer_from_diffid<'a>(
manifest: &'a ImageManifest,
config: &ImageConfiguration,
diffid: &str,
) -> Result<&'a Descriptor> {
let idx = config
.rootfs()
.diff_ids()
.iter()
.position(|x| x.as_str() == diffid)
.ok_or_else(|| anyhow!("Missing {} {}", DIFFID_LABEL, diffid))?;
manifest.layers().get(idx).ok_or_else(|| {
anyhow!(
"diffid position {} exceeds layer count {}",
idx,
manifest.layers().len()
)
})
}
#[context("Parsing manifest layout")]
pub(crate) fn parse_manifest_layout<'a>(
manifest: &'a ImageManifest,
config: &ImageConfiguration,
) -> Result<(
Option<&'a Descriptor>,
Vec<&'a Descriptor>,
Vec<&'a Descriptor>,
)> {
let config_labels = super::labels_of(config);
let first_layer = manifest
.layers()
.first()
.ok_or_else(|| anyhow!("No layers in manifest"))?;
let Some(target_diffid) = config_labels.and_then(|labels| labels.get(DIFFID_LABEL)) else {
return Ok((None, Vec::new(), manifest.layers().iter().collect()));
};
let target_layer = layer_from_diffid(manifest, config, target_diffid.as_str())?;
let mut chunk_layers = Vec::new();
let mut derived_layers = Vec::new();
let mut after_target = false;
// Gather the ostree layer
let ostree_layer = first_layer;
for layer in manifest.layers() {
if layer == target_layer {
if after_target {
anyhow::bail!("Multiple entries for {}", layer.digest());
}
after_target = true;
if layer != ostree_layer {
chunk_layers.push(layer);
}
} else if !after_target {
if layer != ostree_layer {
chunk_layers.push(layer);
}
} else {
derived_layers.push(layer);
}
}
Ok((Some(ostree_layer), chunk_layers, derived_layers))
}
/// Like [`parse_manifest_layout`] but requires the image has an ostree base.
#[context("Parsing manifest layout")]
pub(crate) fn parse_ostree_manifest_layout<'a>(
manifest: &'a ImageManifest,
config: &ImageConfiguration,
) -> Result<(&'a Descriptor, Vec<&'a Descriptor>, Vec<&'a Descriptor>)> {
let (ostree_layer, component_layers, derived_layers) = parse_manifest_layout(manifest, config)?;
let ostree_layer = ostree_layer.ok_or_else(|| {
anyhow!("No {DIFFID_LABEL} label found, not an ostree encapsulated container")
})?;
Ok((ostree_layer, component_layers, derived_layers))
}
/// Find the timestamp of the manifest (or config), ignoring errors.
fn timestamp_of_manifest_or_config(
manifest: &ImageManifest,
config: &ImageConfiguration,
) -> Option<u64> {
// The manifest timestamp seems to not be widely used, but let's
// try it in preference to the config one.
let timestamp = manifest
.annotations()
.as_ref()
.and_then(|a| a.get(oci_image::ANNOTATION_CREATED))
.or_else(|| config.created().as_ref());
// Try to parse the timestamp
timestamp
.map(|t| {
chrono::DateTime::parse_from_rfc3339(t)
.context("Failed to parse manifest timestamp")
.map(|t| t.timestamp() as u64)
})
.transpose()
.log_err_default()
}
impl ImageImporter {
/// The metadata key used in ostree commit metadata to serialize
const CACHED_KEY_MANIFEST_DIGEST: &'static str = "ostree-ext.cached.manifest-digest";
const CACHED_KEY_MANIFEST: &'static str = "ostree-ext.cached.manifest";
const CACHED_KEY_CONFIG: &'static str = "ostree-ext.cached.config";
/// Create a new importer.
#[context("Creating importer")]
pub async fn new(
repo: &ostree::Repo,
imgref: &OstreeImageReference,
mut config: ImageProxyConfig,
) -> Result<Self> {
if imgref.imgref.transport == Transport::ContainerStorage {
// Fetching from containers-storage, may require privileges to read files
merge_default_container_proxy_opts_with_isolation(&mut config, None)?;
} else {
// Apply our defaults to the proxy config
merge_default_container_proxy_opts(&mut config)?;
}
let proxy = ImageProxy::new_with_config(config).await?;
system_repo_journal_print(
repo,
libsystemd::logging::Priority::Info,
&format!("Fetching {}", imgref),
);
let proxy_img = proxy.open_image(&imgref.imgref.to_string()).await?;
let repo = repo.clone();
Ok(ImageImporter {
repo,
proxy,
proxy_img,
target_imgref: None,
no_imgref: false,
ostree_v2024_3: ostree::check_version(2024, 3),
disable_gc: false,
require_bootable: false,
imgref: imgref.clone(),
layer_progress: None,
layer_byte_progress: None,
})
}
/// Write cached data as if the image came from this source.
pub fn set_target(&mut self, target: &OstreeImageReference) {
self.target_imgref = Some(target.clone())
}
/// Do not write the final image ref, but do write refs for shared layers.
/// This is useful in scenarios where you want to "pre-pull" an image,
/// but in such a way that it does not need to be manually removed later.
pub fn set_no_imgref(&mut self) {
self.no_imgref = true;
}
/// Require that the image has the bootable metadata field
pub fn require_bootable(&mut self) {
self.require_bootable = true;
}
/// Override the ostree version being targeted
pub fn set_ostree_version(&mut self, year: u32, v: u32) {
self.ostree_v2024_3 = (year > 2024) || (year == 2024 && v >= 3)
}
/// Do not prune image layers.
pub fn disable_gc(&mut self) {
self.disable_gc = true;
}
/// Determine if there is a new manifest, and if so return its digest.
/// This will also serialize the new manifest and configuration into
/// metadata associated with the image, so that invocations of `[query_cached]`
/// can re-fetch it without accessing the network.
#[context("Preparing import")]
pub async fn prepare(&mut self) -> Result<PrepareResult> {
self.prepare_internal(false).await
}
/// Create a channel receiver that will get notifications for layer fetches.
pub fn request_progress(&mut self) -> Receiver<ImportProgress> {
assert!(self.layer_progress.is_none());
let (s, r) = tokio::sync::mpsc::channel(2);
self.layer_progress = Some(s);
r
}
/// Create a channel receiver that will get notifications for byte-level progress of layer fetches.
pub fn request_layer_progress(
&mut self,
) -> tokio::sync::watch::Receiver<Option<LayerProgress>> {
assert!(self.layer_byte_progress.is_none());
let (s, r) = tokio::sync::watch::channel(None);
self.layer_byte_progress = Some(s);
r
}
/// Serialize the metadata about a pending fetch as detached metadata on the commit object,
/// so it can be retrieved later offline
#[context("Writing cached pending manifest")]
pub(crate) async fn cache_pending(
&self,
commit: &str,
manifest_digest: &Digest,
manifest: &ImageManifest,
config: &ImageConfiguration,
) -> Result<()> {
let commitmeta = glib::VariantDict::new(None);
commitmeta.insert(
Self::CACHED_KEY_MANIFEST_DIGEST,
manifest_digest.to_string(),
);
let cached_manifest = serde_json::to_string(manifest).context("Serializing manifest")?;
commitmeta.insert(Self::CACHED_KEY_MANIFEST, cached_manifest);
let cached_config = serde_json::to_string(config).context("Serializing config")?;
commitmeta.insert(Self::CACHED_KEY_CONFIG, cached_config);
let commitmeta = commitmeta.to_variant();
// Clone these to move into blocking method
let commit = commit.to_string();
let repo = self.repo.clone();
crate::tokio_util::spawn_blocking_cancellable_flatten(move |cancellable| {
repo.write_commit_detached_metadata(&commit, Some(&commitmeta), Some(cancellable))
.map_err(anyhow::Error::msg)
})
.await
}
/// Given existing metadata (manifest, config, previous image statE) generate a PreparedImport structure
/// which e.g. includes a diff of the layers.
fn create_prepared_import(
&mut self,
manifest_digest: Digest,
manifest: ImageManifest,
config: ImageConfiguration,
previous_state: Option<Box<LayeredImageState>>,
previous_imageid: Option<String>,
) -> Result<Box<PreparedImport>> {
let config_labels = super::labels_of(&config);
if self.require_bootable {
let bootable_key = *ostree::METADATA_KEY_BOOTABLE;
let bootable = config_labels.map_or(false, |l| {
l.contains_key(bootable_key) || l.contains_key(BOOTC_LABEL)
});
if !bootable {
anyhow::bail!("Target image does not have {bootable_key} label");
}
let container_arch = config.architecture();
let target_arch = &Arch::default();
if container_arch != target_arch {
anyhow::bail!("Image has architecture {container_arch}; expected {target_arch}");
}
}
let (commit_layer, component_layers, remaining_layers) =
parse_manifest_layout(&manifest, &config)?;
let query = |l: &Descriptor| query_layer(&self.repo, l.clone());
let commit_layer = commit_layer.map(query).transpose()?;
let component_layers = component_layers
.into_iter()
.map(query)
.collect::<Result<Vec<_>>>()?;
let remaining_layers = remaining_layers
.into_iter()
.map(query)
.collect::<Result<Vec<_>>>()?;
let previous_manifest_digest = previous_state.as_ref().map(|s| s.manifest_digest.clone());
let imp = PreparedImport {
manifest_digest,
manifest,
config,
previous_state,
previous_manifest_digest,
previous_imageid,
ostree_layers: component_layers,
ostree_commit_layer: commit_layer,
layers: remaining_layers,
};
Ok(Box::new(imp))
}
/// Determine if there is a new manifest, and if so return its digest.
#[context("Fetching manifest")]
pub(crate) async fn prepare_internal(&mut self, verify_layers: bool) -> Result<PrepareResult> {
match &self.imgref.sigverify {
SignatureSource::ContainerPolicy if skopeo::container_policy_is_default_insecure()? => {
return Err(anyhow!("containers-policy.json specifies a default of `insecureAcceptAnything`; refusing usage"));
}
SignatureSource::OstreeRemote(_) if verify_layers => {
return Err(anyhow!(
"Cannot currently verify layered containers via ostree remote"
));
}
_ => {}
}
let (manifest_digest, manifest) = self.proxy.fetch_manifest(&self.proxy_img).await?;
let manifest_digest = Digest::from_str(&manifest_digest)?;
let new_imageid = manifest.config().digest();
// Query for previous stored state
let (previous_state, previous_imageid) =
if let Some(previous_state) = try_query_image(&self.repo, &self.imgref.imgref)? {
// If the manifest digests match, we're done.
if previous_state.manifest_digest == manifest_digest {
return Ok(PrepareResult::AlreadyPresent(previous_state));
}
// Failing that, if they have the same imageID, we're also done.
let previous_imageid = previous_state.manifest.config().digest();
if previous_imageid == new_imageid {
return Ok(PrepareResult::AlreadyPresent(previous_state));
}
let previous_imageid = previous_imageid.to_string();
(Some(previous_state), Some(previous_imageid))
} else {
(None, None)
};
let config = self.proxy.fetch_config(&self.proxy_img).await?;
// If there is a currently fetched image, cache the new pending manifest+config
// as detached commit metadata, so that future fetches can query it offline.
if let Some(previous_state) = previous_state.as_ref() {
self.cache_pending(
previous_state.merge_commit.as_str(),
&manifest_digest,
&manifest,
&config,
)
.await?;
}
let imp = self.create_prepared_import(
manifest_digest,
manifest,
config,
previous_state,
previous_imageid,
)?;
Ok(PrepareResult::Ready(imp))
}
/// Extract the base ostree commit.
#[context("Unencapsulating base")]
pub(crate) async fn unencapsulate_base(
&mut self,
import: &mut store::PreparedImport,
require_ostree: bool,
write_refs: bool,
) -> Result<()> {
tracing::debug!("Fetching base");
if matches!(self.imgref.sigverify, SignatureSource::ContainerPolicy)
&& skopeo::container_policy_is_default_insecure()?
{
return Err(anyhow!("containers-policy.json specifies a default of `insecureAcceptAnything`; refusing usage"));
}
let remote = match &self.imgref.sigverify {
SignatureSource::OstreeRemote(remote) => Some(remote.clone()),
SignatureSource::ContainerPolicy | SignatureSource::ContainerPolicyAllowInsecure => {
None
}
};
let Some(commit_layer) = import.ostree_commit_layer.as_mut() else {
if require_ostree {
anyhow::bail!(
"No {DIFFID_LABEL} label found, not an ostree encapsulated container"
);
}
return Ok(());
};
let des_layers = self.proxy.get_layer_info(&self.proxy_img).await?;
for layer in import.ostree_layers.iter_mut() {
if layer.commit.is_some() {
continue;
}
if let Some(p) = self.layer_progress.as_ref() {
p.send(ImportProgress::OstreeChunkStarted(layer.layer.clone()))
.await?;
}
let (blob, driver, media_type) = fetch_layer(
&self.proxy,
&self.proxy_img,
&import.manifest,
&layer.layer,
self.layer_byte_progress.as_ref(),
des_layers.as_ref(),
self.imgref.imgref.transport,
)
.await?;
let repo = self.repo.clone();
let target_ref = layer.ostree_ref.clone();
let import_task =
crate::tokio_util::spawn_blocking_cancellable_flatten(move |cancellable| {
let txn = repo.auto_transaction(Some(cancellable))?;
let mut importer = crate::tar::Importer::new_for_object_set(&repo);
let blob = tokio_util::io::SyncIoBridge::new(blob);
let blob = super::unencapsulate::decompressor(&media_type, blob)?;
let mut archive = tar::Archive::new(blob);
importer.import_objects(&mut archive, Some(cancellable))?;
let commit = if write_refs {
let commit = importer.finish_import_object_set()?;
repo.transaction_set_ref(None, &target_ref, Some(commit.as_str()));
tracing::debug!("Wrote {} => {}", target_ref, commit);
Some(commit)
} else {
None
};
txn.commit(Some(cancellable))?;
Ok::<_, anyhow::Error>(commit)
})
.map_err(|e| e.context(format!("Layer {}", layer.layer.digest())));
let commit = super::unencapsulate::join_fetch(import_task, driver).await?;
layer.commit = commit;
if let Some(p) = self.layer_progress.as_ref() {
p.send(ImportProgress::OstreeChunkCompleted(layer.layer.clone()))
.await?;
}
}
if commit_layer.commit.is_none() {
if let Some(p) = self.layer_progress.as_ref() {
p.send(ImportProgress::OstreeChunkStarted(
commit_layer.layer.clone(),
))
.await?;
}
let (blob, driver, media_type) = fetch_layer(
&self.proxy,
&self.proxy_img,
&import.manifest,
&commit_layer.layer,
self.layer_byte_progress.as_ref(),
des_layers.as_ref(),
self.imgref.imgref.transport,
)
.await?;
let repo = self.repo.clone();
let target_ref = commit_layer.ostree_ref.clone();
let import_task =
crate::tokio_util::spawn_blocking_cancellable_flatten(move |cancellable| {
let txn = repo.auto_transaction(Some(cancellable))?;
let mut importer = crate::tar::Importer::new_for_commit(&repo, remote);
let blob = tokio_util::io::SyncIoBridge::new(blob);
let blob = super::unencapsulate::decompressor(&media_type, blob)?;
let mut archive = tar::Archive::new(blob);
importer.import_commit(&mut archive, Some(cancellable))?;
let commit = importer.finish_import_commit();
if write_refs {
repo.transaction_set_ref(None, &target_ref, Some(commit.as_str()));
tracing::debug!("Wrote {} => {}", target_ref, commit);
}
repo.mark_commit_partial(&commit, false)?;
txn.commit(Some(cancellable))?;
Ok::<_, anyhow::Error>(commit)
});
let commit = super::unencapsulate::join_fetch(import_task, driver).await?;
commit_layer.commit = Some(commit);
if let Some(p) = self.layer_progress.as_ref() {
p.send(ImportProgress::OstreeChunkCompleted(
commit_layer.layer.clone(),
))
.await?;
}
};
Ok(())
}
/// Retrieve an inner ostree commit.
///
/// This does not write cached references for each blob, and errors out if
/// the image has any non-ostree layers.
pub async fn unencapsulate(mut self) -> Result<Import> {
let mut prep = match self.prepare_internal(false).await? {
PrepareResult::AlreadyPresent(_) => {
panic!("Should not have image present for unencapsulation")
}
PrepareResult::Ready(r) => r,
};
if !prep.layers.is_empty() {
anyhow::bail!("Image has {} non-ostree layers", prep.layers.len());
}
let deprecated_warning = prep.deprecated_warning().map(ToOwned::to_owned);
self.unencapsulate_base(&mut prep, true, false).await?;
// TODO change the imageproxy API to ensure this happens automatically when
// the image reference is dropped
self.proxy.close_image(&self.proxy_img).await?;
// SAFETY: We know we have a commit
let ostree_commit = prep.ostree_commit_layer.unwrap().commit.unwrap();
let image_digest = prep.manifest_digest;
Ok(Import {
ostree_commit,
image_digest,
deprecated_warning,
})
}
/// Import a layered container image.
///
/// If enabled, this will also prune unused container image layers.
#[context("Importing")]
pub async fn import(
mut self,
mut import: Box<PreparedImport>,
) -> Result<Box<LayeredImageState>> {
if let Some(status) = import.format_layer_status() {
system_repo_journal_print(&self.repo, libsystemd::logging::Priority::Info, &status);
}
// First download all layers for the base image (if necessary) - we need the SELinux policy
// there to label all following layers.
self.unencapsulate_base(&mut import, false, true).await?;
let des_layers = self.proxy.get_layer_info(&self.proxy_img).await?;
let proxy = self.proxy;
let proxy_img = self.proxy_img;
let target_imgref = self.target_imgref.as_ref().unwrap_or(&self.imgref);
let base_commit = import
.ostree_commit_layer
.as_ref()
.map(|c| c.commit.clone().unwrap());
let root_is_transient = if let Some(base) = base_commit.as_ref() {
let rootf = self.repo.read_commit(&base, gio::Cancellable::NONE)?.0;
let rootf = rootf.downcast_ref::<ostree::RepoFile>().unwrap();
crate::ostree_prepareroot::overlayfs_root_enabled(rootf)?
} else {
// For generic images we assume they're using composefs
true
};
tracing::debug!("Base rootfs is transient: {root_is_transient}");
let ostree_ref = ref_for_image(&target_imgref.imgref)?;
let mut layer_commits = Vec::new();
let mut layer_filtered_content: MetaFilteredData = HashMap::new();
let have_derived_layers = !import.layers.is_empty();
for layer in import.layers {
if let Some(c) = layer.commit {
tracing::debug!("Reusing fetched commit {}", c);
layer_commits.push(c.to_string());
} else {
if let Some(p) = self.layer_progress.as_ref() {
p.send(ImportProgress::DerivedLayerStarted(layer.layer.clone()))
.await?;
}
let (blob, driver, media_type) = super::unencapsulate::fetch_layer(
&proxy,
&proxy_img,
&import.manifest,
&layer.layer,
self.layer_byte_progress.as_ref(),
des_layers.as_ref(),
self.imgref.imgref.transport,
)
.await?;
// An important aspect of this is that we SELinux label the derived layers using
// the base policy.
let opts = crate::tar::WriteTarOptions {
base: base_commit.clone(),
selinux: true,
allow_nonusr: root_is_transient,
retain_var: self.ostree_v2024_3,
};
let r = crate::tar::write_tar(
&self.repo,
blob,
media_type,
layer.ostree_ref.as_str(),
Some(opts),
);
let r = super::unencapsulate::join_fetch(r, driver)
.await
.with_context(|| format!("Parsing layer blob {}", layer.layer.digest()))?;
layer_commits.push(r.commit);
if !r.filtered.is_empty() {
let filtered = HashMap::from_iter(r.filtered.into_iter());
tracing::debug!("Found {} filtered toplevels", filtered.len());
layer_filtered_content.insert(layer.layer.digest().to_string(), filtered);
} else {
tracing::debug!("No filtered content");
}
if let Some(p) = self.layer_progress.as_ref() {
p.send(ImportProgress::DerivedLayerCompleted(layer.layer.clone()))
.await?;
}
}
}
// TODO change the imageproxy API to ensure this happens automatically when
// the image reference is dropped
proxy.close_image(&proxy_img).await?;
// We're done with the proxy, make sure it didn't have any errors.
proxy.finalize().await?;
tracing::debug!("finalized proxy");
let serialized_manifest = serde_json::to_string(&import.manifest)?;
let serialized_config = serde_json::to_string(&import.config)?;
let mut metadata = HashMap::new();
metadata.insert(
META_MANIFEST_DIGEST,
import.manifest_digest.to_string().to_variant(),
);
metadata.insert(META_MANIFEST, serialized_manifest.to_variant());
metadata.insert(META_CONFIG, serialized_config.to_variant());
metadata.insert(
"ostree.importer.version",
env!("CARGO_PKG_VERSION").to_variant(),
);
let filtered = layer_filtered_content.to_variant();
metadata.insert(META_FILTERED, filtered);
let metadata = metadata.to_variant();
let timestamp = timestamp_of_manifest_or_config(&import.manifest, &import.config)
.unwrap_or_else(|| chrono::offset::Utc::now().timestamp() as u64);
// Destructure to transfer ownership to thread
let repo = self.repo;
let state = crate::tokio_util::spawn_blocking_cancellable_flatten(
move |cancellable| -> Result<Box<LayeredImageState>> {
use rustix::fd::AsRawFd;
let cancellable = Some(cancellable);
let repo = &repo;
let txn = repo.auto_transaction(cancellable)?;
let devino = ostree::RepoDevInoCache::new();
let repodir = Dir::reopen_dir(&repo.dfd_borrow())?;
let repo_tmp = repodir.open_dir("tmp")?;
let td = cap_std_ext::cap_tempfile::TempDir::new_in(&repo_tmp)?;
let rootpath = "root";
let checkout_mode = if repo.mode() == ostree::RepoMode::Bare {
ostree::RepoCheckoutMode::None
} else {
ostree::RepoCheckoutMode::User
};
let mut checkout_opts = ostree::RepoCheckoutAtOptions {
mode: checkout_mode,
overwrite_mode: ostree::RepoCheckoutOverwriteMode::UnionFiles,
devino_to_csum_cache: Some(devino.clone()),
no_copy_fallback: true,
force_copy_zerosized: true,