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
use crate::blob::{self, BLOB};
use crate::progress::{NoProgress, Progress};
use anyhow::{anyhow, Context, Result};
use async_trait::async_trait;
use flate2::write::GzEncoder;
use futures_util::{stream, StreamExt, TryStreamExt};
use serde_derive::Deserialize;
use std::collections::BTreeMap;
use std::convert::TryInto;
use std::fs::{File, OpenOptions};
use std::path::{Path, PathBuf};
use tar::Builder;
use tokio::io::{AsyncSeekExt, AsyncWriteExt};
#[async_trait]
trait AsyncAppendFile {
async fn append_file_async<P>(&mut self, path: P, file: &mut File) -> std::io::Result<()>
where
P: AsRef<Path> + Send;
async fn append_path_with_name_async<P, N>(&mut self, path: P, name: N) -> std::io::Result<()>
where
P: AsRef<Path> + Send,
N: AsRef<Path> + Send;
async fn append_dir_all_async<P, Q>(&mut self, path: P, src_path: Q) -> std::io::Result<()>
where
P: AsRef<Path> + Send,
Q: AsRef<Path> + Send;
}
#[async_trait]
impl<W: std::io::Write + Send> AsyncAppendFile for Builder<W> {
async fn append_file_async<P>(&mut self, path: P, file: &mut File) -> std::io::Result<()>
where
P: AsRef<Path> + Send,
{
tokio::task::block_in_place(move || self.append_file(path, file))
}
async fn append_path_with_name_async<P, N>(&mut self, path: P, name: N) -> std::io::Result<()>
where
P: AsRef<Path> + Send,
N: AsRef<Path> + Send,
{
tokio::task::block_in_place(move || self.append_path_with_name(path, name))
}
async fn append_dir_all_async<P, Q>(&mut self, path: P, src_path: Q) -> std::io::Result<()>
where
P: AsRef<Path> + Send,
Q: AsRef<Path> + Send,
{
tokio::task::block_in_place(move || self.append_dir_all(path, src_path))
}
}
fn create_tarfile<P: AsRef<Path> + std::fmt::Debug>(tarfile: P) -> Result<File> {
OpenOptions::new()
.write(true)
.read(true)
.truncate(true)
.create(true)
.open(tarfile.as_ref())
.map_err(|err| anyhow!("Cannot create tarfile {:?}: {}", tarfile, err))
}
fn open_tarfile<P: AsRef<Path> + std::fmt::Debug>(tarfile: P) -> Result<File> {
OpenOptions::new()
.read(true)
.open(tarfile.as_ref())
.map_err(|err| anyhow!("Cannot open tarfile {:?}: {}", tarfile, err))
}
fn archive_path(path: &Path) -> Result<PathBuf> {
let leading_slash = std::path::MAIN_SEPARATOR.to_string();
Ok(Path::new("root").join(&path.strip_prefix(leading_slash)?))
}
fn add_directory_and_parents<W: std::io::Write>(
archive: &mut tar::Builder<W>,
to: &Path,
) -> Result<()> {
let mut parents: Vec<&Path> = to.ancestors().collect::<Vec<&Path>>();
parents.reverse();
if to.is_relative() {
return Err(anyhow!(
"Cannot add 'to = {}'; absolute path required",
to.to_string_lossy()
));
}
for parent in parents {
let dst = archive_path(parent)?;
archive.append_dir(&dst, ".")?;
}
Ok(())
}
#[derive(Deserialize, Debug)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum PackageSource {
Local {
blobs: Option<Vec<PathBuf>>,
rust: Option<RustPackage>,
#[serde(default)]
paths: Vec<MappedPath>,
},
Prebuilt {
repo: String,
commit: String,
sha256: String,
},
Composite { packages: Vec<String> },
Manual,
}
impl PackageSource {
fn rust_package(&self) -> Option<&RustPackage> {
match self {
PackageSource::Local {
rust: Some(rust_pkg),
..
} => Some(rust_pkg),
_ => None,
}
}
fn blobs(&self) -> Option<&[PathBuf]> {
match self {
PackageSource::Local {
blobs: Some(blobs), ..
} => Some(blobs),
_ => None,
}
}
}
#[derive(Deserialize, Debug, Clone)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum PackageOutput {
Zone {
#[serde(default)]
intermediate_only: bool,
},
Tarball,
}
#[derive(Deserialize, Debug)]
pub struct Package {
pub service_name: String,
pub source: PackageSource,
pub output: PackageOutput,
pub only_for_targets: Option<BTreeMap<String, String>>,
#[serde(default)]
pub setup_hint: Option<String>,
}
async fn new_zone_archive_builder(
package_name: &str,
output_directory: &Path,
) -> Result<tar::Builder<GzEncoder<File>>> {
let tarfile = output_directory.join(format!("{}.tar.gz", package_name));
let file = create_tarfile(tarfile)?;
let gzw = GzEncoder::new(file, flate2::Compression::fast());
let mut archive = Builder::new(gzw);
archive.mode(tar::HeaderMode::Deterministic);
let mut root_json = tokio::fs::File::from_std(tempfile::tempfile()?);
let contents = r#"{"v":"1","t":"layer"}"#;
root_json.write_all(contents.as_bytes()).await?;
root_json.seek(std::io::SeekFrom::Start(0)).await?;
archive
.append_file_async(&Path::new("oxide.json"), &mut root_json.into_std().await)
.await?;
Ok(archive)
}
impl Package {
pub fn get_output_path(&self, name: &str, output_directory: &Path) -> PathBuf {
output_directory.join(self.get_output_file(name))
}
pub fn get_output_file(&self, name: &str) -> String {
match self.output {
PackageOutput::Zone { .. } => format!("{}.tar.gz", name),
PackageOutput::Tarball => format!("{}.tar", name),
}
}
pub async fn create(&self, name: &str, output_directory: &Path) -> Result<File> {
self.create_internal(&NoProgress, name, output_directory)
.await
}
pub fn get_total_work(&self) -> u64 {
let progress_total = match &self.source {
PackageSource::Local { blobs, rust, paths } => {
let blob_work = blobs.as_ref().map(|b| b.len() + 1).unwrap_or(0);
let rust_work = rust.as_ref().map(|r| r.binary_names.len()).unwrap_or(0);
let paths_work = paths
.iter()
.map(|path| {
walkdir::WalkDir::new(&path.from)
.follow_links(true)
.into_iter()
.count()
})
.sum::<usize>();
rust_work + blob_work + paths_work
}
_ => 1,
};
progress_total.try_into().unwrap()
}
pub async fn create_with_progress(
&self,
progress: &impl Progress,
name: &str,
output_directory: &Path,
) -> Result<File> {
self.create_internal(progress, name, output_directory).await
}
async fn create_internal(
&self,
progress: &impl Progress,
name: &str,
output_directory: &Path,
) -> Result<File> {
match self.output {
PackageOutput::Zone { .. } => {
self.create_zone_package(progress, name, output_directory)
.await
}
PackageOutput::Tarball => {
self.create_tarball_package(progress, name, output_directory)
.await
}
}
}
async fn add_paths<W: std::io::Write + Send + Sync>(
&self,
progress: &impl Progress,
archive: &mut Builder<W>,
paths: &Vec<MappedPath>,
) -> Result<()> {
progress.set_message("adding paths".into());
for path in paths {
match self.output {
PackageOutput::Zone { .. } => {
add_directory_and_parents(archive, path.to.parent().unwrap())?;
}
PackageOutput::Tarball => {}
}
if !path.from.exists() {
return Err(anyhow!(
"Cannot add path \"{}\" to package \"{}\" because it does not exist",
path.from.to_string_lossy(),
self.service_name,
));
}
let from_root = std::fs::canonicalize(&path.from).map_err(|e| {
anyhow!(
"failed to canonicalize \"{}\": {}",
path.from.to_string_lossy(),
e
)
})?;
let entries = walkdir::WalkDir::new(&from_root)
.follow_links(true)
.sort_by_file_name();
for entry in entries {
let entry = entry?;
let dst = &path.to.join(entry.path().strip_prefix(&from_root)?);
let dst = match self.output {
PackageOutput::Zone { .. } => {
archive_path(dst)?
}
PackageOutput::Tarball => dst.to_path_buf(),
};
if entry.file_type().is_dir() {
archive.append_dir(&dst, ".")?;
} else if entry.file_type().is_file() {
archive
.append_path_with_name_async(entry.path(), &dst)
.await
.context(format!(
"Failed to add file '{}' to '{}'",
entry.path().display(),
dst.display()
))?;
} else {
panic!(
"Unsupported file type: {:?} for {:?}",
entry.file_type(),
entry
);
}
progress.increment(1);
}
}
Ok(())
}
async fn add_rust<W: std::io::Write + Send>(
&self,
progress: &impl Progress,
archive: &mut Builder<W>,
) -> Result<()> {
if let Some(rust_pkg) = self.source.rust_package() {
let dst = match self.output {
PackageOutput::Zone { .. } => {
let dst = Path::new("/opt/oxide").join(&self.service_name).join("bin");
add_directory_and_parents(archive, &dst)?;
archive_path(&dst)?
}
PackageOutput::Tarball => PathBuf::from(""),
};
rust_pkg
.add_binaries_to_archive(progress, archive, &dst)
.await?;
}
Ok(())
}
async fn add_blobs<W: std::io::Write + Send>(
&self,
progress: &impl Progress,
archive: &mut Builder<W>,
download_directory: &Path,
destination_path: &Path,
) -> Result<()> {
if let Some(blobs) = self.source.blobs() {
progress.set_message("downloading blobs".into());
let blobs_path = download_directory.join(&self.service_name);
std::fs::create_dir_all(&blobs_path)?;
stream::iter(blobs.iter())
.map(Ok)
.try_for_each_concurrent(None, |blob| {
let blob_path = blobs_path.join(blob);
async move {
blob::download(progress, &blob.to_string_lossy(), &blob_path)
.await
.with_context(|| {
format!("failed to download blob: {}", blob.to_string_lossy())
})?;
progress.increment(1);
Ok::<_, anyhow::Error>(())
}
})
.await?;
progress.set_message("adding blobs".into());
archive
.append_dir_all_async(&destination_path, &blobs_path)
.await?;
progress.increment(1);
}
Ok(())
}
async fn create_zone_package(
&self,
progress: &impl Progress,
name: &str,
output_directory: &Path,
) -> Result<File> {
let mut archive = new_zone_archive_builder(name, output_directory).await?;
match &self.source {
PackageSource::Local { paths, .. } => {
self.add_paths(progress, &mut archive, paths).await?;
self.add_rust(progress, &mut archive).await?;
let blob_dst = Path::new("/opt/oxide").join(&self.service_name).join(BLOB);
self.add_blobs(
progress,
&mut archive,
output_directory,
&archive_path(&blob_dst)?,
)
.await?;
}
PackageSource::Composite { packages } => {
let tmp = tempfile::tempdir()?;
for component_package in packages {
let component_path = output_directory.join(component_package);
let gzr = flate2::read::GzDecoder::new(open_tarfile(&component_path)?);
if gzr.header().is_none() {
return Err(anyhow!("Missing gzip header from {}. Note that composite packages can currently only consist of zone images", component_path.display()));
}
let mut component_reader = tar::Archive::new(gzr);
let entries = component_reader.entries()?;
for entry in entries {
let mut entry = entry?;
let entry_path = entry.path()?;
if entry_path == Path::new("oxide.json") {
continue;
}
let entry_unpack_path = tmp.path().join(entry_path.strip_prefix("root/")?);
entry.unpack(&entry_unpack_path)?;
let entry_path = entry.path()?;
assert!(entry_unpack_path.exists());
archive
.append_path_with_name_async(entry_unpack_path, entry_path)
.await?;
}
}
}
_ => {
return Err(anyhow!(
"Cannot create a zone package with source: {:?}",
self.source
));
}
}
let file = archive
.into_inner()
.map_err(|err| anyhow!("Failed to finalize archive: {}", err))?;
Ok(file.finish()?)
}
async fn create_tarball_package(
&self,
progress: &impl Progress,
name: &str,
output_directory: &Path,
) -> Result<File> {
let tarfile = self.get_output_path(name, output_directory);
let file = create_tarfile(&tarfile)?;
let mut archive = Builder::new(file);
archive.mode(tar::HeaderMode::Deterministic);
match &self.source {
PackageSource::Local { paths, .. } => {
self.add_paths(progress, &mut archive, paths).await?;
self.add_rust(progress, &mut archive).await?;
self.add_blobs(progress, &mut archive, output_directory, Path::new(BLOB))
.await?;
Ok(archive
.into_inner()
.map_err(|err| anyhow!("Failed to finalize archive: {}", err))?)
}
_ => Err(anyhow!("Cannot create non-local tarball")),
}
}
}
#[derive(Deserialize, Debug)]
pub struct RustPackage {
pub binary_names: Vec<String>,
pub release: bool,
}
impl RustPackage {
async fn add_binaries_to_archive<W: std::io::Write + Send>(
&self,
progress: &impl Progress,
archive: &mut tar::Builder<W>,
dst_directory: &Path,
) -> Result<()> {
for name in &self.binary_names {
progress.set_message(format!("adding rust binary: {name}").into());
archive
.append_path_with_name_async(
Self::local_binary_path(name, self.release),
dst_directory.join(&name),
)
.await
.map_err(|err| anyhow!("Cannot append binary to tarfile: {}", err))?;
progress.increment(1);
}
Ok(())
}
fn local_binary_path(name: &str, release: bool) -> PathBuf {
format!(
"target/{}/{}",
if release { "release" } else { "debug" },
name,
)
.into()
}
}
#[derive(Deserialize, Debug)]
pub struct MappedPath {
pub from: PathBuf,
pub to: PathBuf,
}