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
use super::*;
use anyhow::{anyhow, Context};
use containers_image_proxy::{ImageProxy, OpenedImage};
use fn_error_context::context;
use futures_util::Future;
use oci_spec::image as oci_image;
use tokio::io::{AsyncBufRead, AsyncRead};
use tracing::{event, instrument, Level};
#[derive(Copy, Clone, Debug, Default)]
pub struct UnencapsulationProgress {
pub processed_bytes: u64,
}
type Progress = tokio::sync::watch::Sender<UnencapsulationProgress>;
#[pin_project::pin_project]
#[derive(Debug)]
struct ProgressReader<T> {
#[pin]
reader: T,
#[pin]
progress: Option<Progress>,
}
impl<T: AsyncRead> AsyncRead for ProgressReader<T> {
fn poll_read(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &mut tokio::io::ReadBuf<'_>,
) -> std::task::Poll<std::io::Result<()>> {
let this = self.project();
let len = buf.filled().len();
match this.reader.poll_read(cx, buf) {
v @ std::task::Poll::Ready(Ok(_)) => {
if let Some(progress) = this.progress.as_ref().get_ref() {
let state = {
let mut state = *progress.borrow();
let newlen = buf.filled().len();
debug_assert!(newlen >= len);
let read = (newlen - len) as u64;
state.processed_bytes += read;
state
};
let _ = progress.send(state);
}
v
}
o => o,
}
}
}
async fn fetch_manifest_impl(
proxy: &mut ImageProxy,
imgref: &OstreeImageReference,
) -> Result<(oci_spec::image::ImageManifest, String)> {
let oi = &proxy.open_image(&imgref.imgref.to_string()).await?;
let (digest, raw_manifest) = proxy.fetch_manifest(oi).await?;
proxy.close_image(oi).await?;
Ok((serde_json::from_slice(&raw_manifest)?, digest))
}
#[context("Fetching manifest")]
pub async fn fetch_manifest(
imgref: &OstreeImageReference,
) -> Result<(oci_spec::image::ImageManifest, String)> {
let mut proxy = ImageProxy::new().await?;
fetch_manifest_impl(&mut proxy, imgref).await
}
#[derive(Debug)]
pub struct Import {
pub ostree_commit: String,
pub image_digest: String,
}
fn require_one_layer_blob(manifest: &oci_image::ImageManifest) -> Result<&oci_image::Descriptor> {
let n = manifest.layers().len();
if let Some(layer) = manifest.layers().get(0) {
if n > 1 {
Err(anyhow!("Expected 1 layer, found {}", n))
} else {
Ok(layer)
}
} else {
unreachable!()
}
}
pub(crate) async fn join_fetch<T: std::fmt::Debug>(
worker: impl Future<Output = Result<T>>,
driver: impl Future<Output = Result<()>>,
) -> Result<T> {
let (worker, driver) = tokio::join!(worker, driver);
match (worker, driver) {
(Ok(t), Ok(())) => Ok(t),
(Err(worker), Err(driver)) => {
let text = driver.root_cause().to_string();
if text.ends_with("broken pipe") {
Err(worker)
} else {
Err(worker.context(format!("proxy failure: {} and client error", text)))
}
}
(Ok(_), Err(driver)) => Err(driver),
(Err(worker), Ok(())) => Err(worker),
}
}
#[derive(Debug, Default)]
pub struct UnencapsulateOptions {
pub progress: Option<tokio::sync::watch::Sender<UnencapsulationProgress>>,
}
#[context("Importing {}", imgref)]
#[instrument(skip(repo, options))]
pub async fn unencapsulate(
repo: &ostree::Repo,
imgref: &OstreeImageReference,
options: Option<UnencapsulateOptions>,
) -> Result<Import> {
let mut proxy = ImageProxy::new().await?;
let oi = &proxy.open_image(&imgref.imgref.to_string()).await?;
let (image_digest, raw_manifest) = proxy.fetch_manifest(oi).await?;
let manifest = serde_json::from_slice(&raw_manifest)?;
let ostree_commit =
unencapsulate_from_manifest_impl(repo, &mut proxy, imgref, oi, &manifest, options, false)
.await?;
proxy.close_image(oi).await?;
Ok(Import {
ostree_commit,
image_digest,
})
}
fn new_async_decompressor<'a>(
media_type: &oci_image::MediaType,
src: impl AsyncBufRead + Send + Unpin + 'a,
) -> Result<Box<dyn AsyncBufRead + Send + Unpin + 'a>> {
match media_type {
oci_image::MediaType::ImageLayerGzip => Ok(Box::new(tokio::io::BufReader::new(
async_compression::tokio::bufread::GzipDecoder::new(src),
))),
oci_image::MediaType::ImageLayer => Ok(Box::new(src)),
o => Err(anyhow::anyhow!("Unhandled layer type: {}", o)),
}
}
#[instrument(skip(proxy, img, layer))]
pub(crate) async fn fetch_layer_decompress<'a>(
proxy: &'a mut ImageProxy,
img: &OpenedImage,
layer: &oci_image::Descriptor,
) -> Result<(
Box<dyn AsyncBufRead + Send + Unpin>,
impl Future<Output = Result<()>> + 'a,
)> {
tracing::debug!("fetching {}", layer.digest());
let (blob, driver) = proxy
.get_blob(img, layer.digest().as_str(), layer.size() as u64)
.await?;
let blob = new_async_decompressor(layer.media_type(), blob)?;
Ok((blob, driver))
}
pub(crate) async fn unencapsulate_from_manifest_impl(
repo: &ostree::Repo,
proxy: &mut ImageProxy,
imgref: &OstreeImageReference,
oi: &containers_image_proxy::OpenedImage,
manifest: &oci_spec::image::ImageManifest,
options: Option<UnencapsulateOptions>,
ignore_layered: bool,
) -> Result<String> {
if matches!(imgref.sigverify, SignatureSource::ContainerPolicy)
&& skopeo::container_policy_is_default_insecure()?
{
return Err(anyhow!("containers-policy.json specifies a default of `insecureAcceptAnything`; refusing usage"));
}
let options = options.unwrap_or_default();
let layer = if ignore_layered {
manifest
.layers()
.get(0)
.ok_or_else(|| anyhow!("No layers in image"))?
} else {
require_one_layer_blob(manifest)?
};
event!(
Level::DEBUG,
"target blob digest:{} size: {}",
layer.digest().as_str(),
layer.size()
);
let (blob, driver) = fetch_layer_decompress(proxy, oi, layer).await?;
let blob = ProgressReader {
reader: blob,
progress: options.progress,
};
let mut taropts: crate::tar::TarImportOptions = Default::default();
match &imgref.sigverify {
SignatureSource::OstreeRemote(remote) => taropts.remote = Some(remote.clone()),
SignatureSource::ContainerPolicy | SignatureSource::ContainerPolicyAllowInsecure => {}
}
let import = crate::tar::import_tar(repo, blob, Some(taropts));
let ostree_commit = join_fetch(import, driver)
.await
.with_context(|| format!("Parsing blob {}", layer.digest()))?;
event!(Level::DEBUG, "created commit {}", ostree_commit);
Ok(ostree_commit)
}
#[context("Importing {}", imgref)]
#[instrument(skip(repo, options, manifest))]
pub async fn unencapsulate_from_manifest(
repo: &ostree::Repo,
imgref: &OstreeImageReference,
manifest: &oci_spec::image::ImageManifest,
options: Option<UnencapsulateOptions>,
) -> Result<String> {
let mut proxy = ImageProxy::new().await?;
let oi = &proxy.open_image(&imgref.imgref.to_string()).await?;
let r =
unencapsulate_from_manifest_impl(repo, &mut proxy, imgref, oi, manifest, options, false)
.await?;
proxy.close_image(oi).await?;
proxy.finalize().await?;
Ok(r)
}