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
use anyhow::{anyhow, bail, Context, Result};
use reqwest::{blocking, StatusCode, Url};
use serde::Deserialize;
use std::collections::HashMap;
use std::fmt::{Display, Formatter};
use std::fs::OpenOptions;
use std::io::{Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};
use std::thread::sleep;
use std::time::Duration;
use crate::cmdline::*;
use crate::osmet::*;
const HTTP_COMPLETION_TIMEOUT: Duration = Duration::from_secs(4 * 60 * 60);
const DEFAULT_STREAM_BASE_URL: &str = "https://builds.coreos.fedoraproject.org/streams/";
const OSMET_FILES_DIR: &str = "/run/coreos-installer/osmet";
pub trait ImageLocation: Display {
fn sources(&self) -> Result<Vec<ImageSource>>;
fn require_signature(&self) -> bool {
true
}
}
#[derive(Debug)]
pub struct FileLocation {
image_path: String,
sig_path: String,
}
pub struct OsmetLocation {
osmet_path: PathBuf,
architecture: String,
sector_size: u32,
description: String,
}
#[derive(Debug)]
pub struct UrlLocation {
image_url: Url,
sig_url: Url,
artifact_type: String,
retries: FetchRetries,
}
#[derive(Debug)]
pub struct StreamLocation {
stream_base_url: Option<Url>,
stream: String,
stream_url: Url,
architecture: String,
platform: String,
format: String,
retries: FetchRetries,
}
pub struct ImageSource {
pub reader: Box<dyn Read>,
pub length_hint: Option<u64>,
pub signature: Option<Vec<u8>>,
pub filename: String,
pub artifact_type: String,
}
impl FileLocation {
pub fn new(path: &str) -> Self {
Self {
image_path: path.to_string(),
sig_path: format!("{}.sig", path),
}
}
}
impl Display for FileLocation {
fn fmt(&self, f: &mut Formatter<'_>) -> ::std::fmt::Result {
write!(
f,
"Copying image from {}\nReading signature from {}",
self.image_path, self.sig_path
)
}
}
impl ImageLocation for FileLocation {
fn sources(&self) -> Result<Vec<ImageSource>> {
let mut out = OpenOptions::new()
.read(true)
.open(&self.image_path)
.context("opening source image file")?;
let length = out
.seek(SeekFrom::End(0))
.context("seeking source image file")?;
out.seek(SeekFrom::Start(0))
.context("seeking source image file")?;
let signature = match OpenOptions::new().read(true).open(&self.sig_path) {
Ok(mut file) => {
let mut sig_vec = Vec::new();
file.read_to_end(&mut sig_vec)
.context("reading signature file")?;
Some(sig_vec)
}
Err(err) => {
eprintln!("Couldn't read signature file: {}", err);
None
}
};
let filename = Path::new(&self.image_path)
.file_name()
.context("extracting filename")?
.to_string_lossy()
.to_string();
Ok(vec![ImageSource {
reader: Box::new(out),
length_hint: Some(length),
signature,
filename,
artifact_type: "disk".to_string(),
}])
}
}
impl UrlLocation {
pub fn new(url: &Url, retries: FetchRetries) -> Self {
let mut sig_url = url.clone();
sig_url.set_path(&format!("{}.sig", sig_url.path()));
Self::new_full(url, &sig_url, "disk", retries)
}
fn new_full(url: &Url, sig_url: &Url, artifact_type: &str, retries: FetchRetries) -> Self {
Self {
image_url: url.clone(),
sig_url: sig_url.clone(),
artifact_type: artifact_type.to_string(),
retries,
}
}
fn fetch_signature(&self) -> Result<Vec<u8>> {
let client = new_http_client()?;
let mut resp = http_get(client, self.sig_url.as_str(), self.retries)
.context("fetching signature URL")?;
let mut sig_bytes = Vec::new();
resp.read_to_end(&mut sig_bytes)
.context("reading signature content")?;
Ok(sig_bytes)
}
}
impl Display for UrlLocation {
fn fmt(&self, f: &mut Formatter<'_>) -> ::std::fmt::Result {
write!(
f,
"Downloading image from {}\nDownloading signature from {}",
self.image_url, self.sig_url
)
}
}
impl ImageLocation for UrlLocation {
fn sources(&self) -> Result<Vec<ImageSource>> {
let signature = self
.fetch_signature()
.map_err(|e| eprintln!("Failed to fetch signature: {}", e))
.ok();
let client = new_http_client()?;
let resp = http_get(client, self.image_url.as_str(), self.retries)
.context("fetching image URL")?;
match resp.status() {
StatusCode::OK => (),
s => bail!("image fetch failed: {}", s),
};
let length_hint = resp.content_length();
let filename = resp
.url()
.path_segments()
.context("splitting image URL")?
.next_back()
.context("walking image URL")?
.to_string();
Ok(vec![ImageSource {
reader: Box::new(resp),
length_hint,
signature,
filename,
artifact_type: self.artifact_type.clone(),
}])
}
}
impl StreamLocation {
pub fn new(
stream: &str,
architecture: &str,
platform: &str,
format: &str,
base_url: Option<&Url>,
retries: FetchRetries,
) -> Result<Self> {
Ok(Self {
stream_base_url: base_url.cloned(),
stream: stream.to_string(),
stream_url: build_stream_url(stream, base_url)?,
architecture: architecture.to_string(),
platform: platform.to_string(),
format: format.to_string(),
retries,
})
}
}
impl Display for StreamLocation {
fn fmt(&self, f: &mut Formatter<'_>) -> ::std::fmt::Result {
if self.stream_base_url.is_some() {
write!(
f,
"Downloading image ({}) and signature referenced from {}",
self.format, self.stream_url
)
} else {
write!(
f,
"Downloading {} image ({}) and signature",
self.stream, self.format
)
}
}
}
impl ImageLocation for StreamLocation {
fn sources(&self) -> Result<Vec<ImageSource>> {
let client = new_http_client()?;
let stream = fetch_stream(client, &self.stream_url, self.retries)?;
let artifacts = stream
.architectures
.get(&self.architecture)
.map(|arch| arch.artifacts.get(&self.platform))
.unwrap_or(None)
.map(|platform| platform.formats.get(&self.format))
.unwrap_or(None)
.with_context(|| {
format!(
"couldn't find architecture {}, platform {}, format {} in stream metadata",
self.architecture, self.platform, self.format
)
})?;
let mut sources: Vec<ImageSource> = Vec::new();
for (artifact_type, artifact) in artifacts.iter() {
let artifact_url = Url::parse(&artifact.location)
.context("parsing artifact URL from stream metadata")?;
let signature_url = Url::parse(&artifact.signature)
.context("parsing signature URL from stream metadata")?;
let mut artifact_sources =
UrlLocation::new_full(&artifact_url, &signature_url, &artifact_type, self.retries)
.sources()?;
sources.append(&mut artifact_sources);
}
sources.sort_by_key(|k| k.artifact_type.to_string());
Ok(sources)
}
}
impl OsmetLocation {
pub fn new(architecture: &str, sector_size: u32) -> Result<Option<Self>> {
let osmet_dir = Path::new(OSMET_FILES_DIR);
if !osmet_dir.exists() {
return Ok(None);
}
if let Some((osmet_path, description)) =
find_matching_osmet_in_dir(osmet_dir, architecture, sector_size)?
{
Ok(Some(Self {
osmet_path,
architecture: architecture.into(),
sector_size,
description,
}))
} else {
Ok(None)
}
}
}
impl Display for OsmetLocation {
fn fmt(&self, f: &mut Formatter<'_>) -> ::std::fmt::Result {
write!(
f,
"Installing {} {} ({}-byte sectors)",
self.description, self.architecture, self.sector_size
)
}
}
impl ImageLocation for OsmetLocation {
fn sources(&self) -> Result<Vec<ImageSource>> {
let unpacker = OsmetUnpacker::new_from_sysroot(Path::new(&self.osmet_path))?;
let filename = {
let stem = self.osmet_path.file_stem().ok_or_else(|| {
anyhow!(
"can't create new .raw filename from osmet path {:?}",
&self.osmet_path
)
})?;
let mut filename: String = stem
.to_str()
.ok_or_else(|| anyhow!("non-UTF-8 osmet file stem: {:?}", stem))?
.into();
filename.push_str(".raw");
filename
};
let length = unpacker.length();
Ok(vec![ImageSource {
reader: Box::new(unpacker),
length_hint: Some(length),
signature: None,
filename,
artifact_type: "disk".to_string(),
}])
}
fn require_signature(&self) -> bool {
false
}
}
pub fn list_stream(config: &ListStreamConfig) -> Result<()> {
#[derive(PartialEq, Eq, PartialOrd, Ord)]
struct Row<'a> {
architecture: &'a str,
platform: &'a str,
format: &'a str,
}
let client = new_http_client()?;
let stream_url = build_stream_url(&config.stream, config.stream_base_url.as_ref())?;
let stream = fetch_stream(client, &stream_url, FetchRetries::None)?;
let mut rows: Vec<Row> = Vec::new();
for (architecture_name, architecture) in stream.architectures.iter() {
for (platform_name, platform) in architecture.artifacts.iter() {
for format_name in platform.formats.keys() {
rows.push(Row {
architecture: architecture_name,
platform: platform_name,
format: format_name,
});
}
}
}
rows.sort();
rows.insert(
0,
Row {
architecture: "Architecture",
platform: "Platform",
format: "Format",
},
);
let mut widths: [usize; 2] = [0; 2];
for row in &rows {
widths[0] = widths[0].max(row.architecture.len());
widths[1] = widths[1].max(row.platform.len());
}
for row in &rows {
println!(
"{:3$} {:4$} {}",
row.architecture, row.platform, row.format, widths[0], widths[1]
);
}
Ok(())
}
fn build_stream_url(stream: &str, base_url: Option<&Url>) -> Result<Url> {
base_url
.unwrap_or(&Url::parse(DEFAULT_STREAM_BASE_URL).unwrap())
.join(&format!("{}.json", stream))
.context("building stream URL")
}
fn fetch_stream(client: blocking::Client, url: &Url, retries: FetchRetries) -> Result<Stream> {
let resp = http_get(client, url.as_str(), retries).context("fetching stream metadata")?;
match resp.status() {
StatusCode::OK => (),
s => bail!("stream metadata fetch from {} failed: {}", url, s),
};
let stream: Stream = serde_json::from_reader(resp).context("decoding stream metadata")?;
Ok(stream)
}
pub fn new_http_client() -> Result<blocking::Client> {
blocking::ClientBuilder::new()
.timeout(HTTP_COMPLETION_TIMEOUT)
.build()
.context("building HTTP client")
}
pub fn http_get(
client: blocking::Client,
url: &str,
retries: FetchRetries,
) -> Result<blocking::Response> {
const RETRY_STATUS_CODES: [u16; 6] = [408, 429, 500, 502, 503, 504];
let mut delay = 1;
let (infinite, mut tries) = match retries {
FetchRetries::Infinite => (true, 0),
FetchRetries::Finite(n) => (false, n.get() + 1),
FetchRetries::None => (false, 1),
};
loop {
let err: anyhow::Error = match client.get(url).send() {
Err(err) => err.into(),
Ok(resp) => match resp.status().as_u16() {
code if RETRY_STATUS_CODES.contains(&code) => anyhow!(
"HTTP {} {}",
code,
resp.status().canonical_reason().unwrap_or("")
),
_ => {
return resp
.error_for_status()
.with_context(|| format!("fetching '{}'", url));
}
},
};
if !infinite {
tries -= 1;
if tries == 0 {
return Err(err).with_context(|| format!("fetching '{}'", url));
}
}
eprintln!("Error fetching '{}': {}", url, err);
eprintln!("Sleeping {}s and retrying...", delay);
sleep(Duration::from_secs(delay));
delay = std::cmp::min(delay * 2, 10 * 60);
}
}
#[derive(Debug, Deserialize)]
struct Stream {
architectures: HashMap<String, Arch>,
}
#[derive(Debug, Deserialize)]
struct Arch {
artifacts: HashMap<String, Platform>,
}
#[derive(Debug, Deserialize)]
struct Platform {
formats: HashMap<String, HashMap<String, Artifact>>,
}
#[derive(Debug, Deserialize)]
struct Artifact {
location: String,
signature: String,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_new_http_client() {
let _ = new_http_client().unwrap();
}
}