-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathmain.rs
More file actions
659 lines (623 loc) · 23.7 KB
/
main.rs
File metadata and controls
659 lines (623 loc) · 23.7 KB
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
//! Command-line control utility for composefs repositories and images.
//!
//! `cfsctl` provides a comprehensive interface for managing composefs repositories,
//! creating and mounting filesystem images, handling OCI containers, and performing
//! repository maintenance operations like garbage collection.
use std::{
fs::create_dir_all,
path::{Path, PathBuf},
sync::Arc,
};
use anyhow::Result;
use clap::{Parser, Subcommand, ValueEnum};
use rustix::fs::CWD;
use composefs_boot::{write_boot, BootOps};
use composefs::{
fsverity::{FsVerityHashValue, Sha256HashValue, Sha512HashValue},
repository::Repository,
};
/// cfsctl
#[derive(Debug, Parser)]
#[clap(name = "cfsctl", version)]
pub struct App {
/// Operate on repo at path
#[clap(long, group = "repopath")]
repo: Option<PathBuf>,
/// Operate on repo at standard user location $HOME/.var/lib/composefs
#[clap(long, group = "repopath")]
user: bool,
/// Operate on repo at standard system location /sysroot/composefs
#[clap(long, group = "repopath")]
system: bool,
/// What hash digest type to use for composefs repo
#[clap(long, value_enum, default_value_t = HashType::Sha512)]
hash: HashType,
/// Sets the repository to insecure before running any operation and
/// prepend '?' to the composefs kernel command line when writing
/// boot entry.
#[clap(long)]
insecure: bool,
#[clap(subcommand)]
cmd: Command,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, ValueEnum, Default)]
enum HashType {
Sha256,
#[default]
Sha512,
}
/// Common options for operations using OCI config manifest streams that may transform the image rootfs
#[derive(Debug, Parser)]
struct OCIConfigFilesystemOptions {
#[clap(flatten)]
base_config: OCIConfigOptions,
/// Whether bootable transformation should be performed on the image rootfs
#[clap(long)]
bootable: bool,
}
/// Common options for operations using OCI config manifest streams
#[derive(Debug, Parser)]
struct OCIConfigOptions {
/// the name of the target OCI manifest stream, either a stream ID in format oci-config-<hash_type>:<hash_digest> or a reference in 'ref/'
config_name: String,
/// verity digest for the manifest stream to be verified against
config_verity: Option<String>,
}
#[cfg(feature = "oci")]
#[derive(Debug, Subcommand)]
enum OciCommand {
/// Stores a tar layer file as a splitstream in the repository.
ImportLayer {
digest: String,
name: Option<String>,
},
/// Imports a complete image from a splitfdstream server into the repository.
ImportImageSplitfdstream {
/// Path to the splitfdstream server socket
socket: PathBuf,
/// The image ID (manifest digest or tag)
image_id: String,
/// Tag name for imported image
#[clap(long)]
tag: Option<String>,
},
/// Lists the contents of a tar stream
LsLayer {
/// the name of the stream to list, either a stream ID in format oci-config-<hash_type>:<hash_digest> or a reference in 'ref/'
name: String,
},
/// Dump full content of the rootfs of a stored OCI image to a composefs dumpfile and write to stdout
Dump {
#[clap(flatten)]
config_opts: OCIConfigFilesystemOptions,
},
/// Pull an OCI image to be stored in repo then prints the stream and verity digest of its manifest
Pull {
/// source image reference, as accepted by skopeo
image: String,
/// optional reference name for the manifest, use as 'ref/<name>' elsewhere
name: Option<String>,
},
/// List all tagged OCI images in the repository
#[clap(name = "images")]
ListImages,
/// Show information about an OCI image
#[clap(name = "inspect")]
Inspect {
/// Image reference (tag name or manifest digest)
image: String,
},
/// Tag an image with a new name
Tag {
/// Manifest digest (sha256:...)
manifest_digest: String,
/// Tag name to assign
name: String,
},
/// Remove a tag from an image
Untag {
/// Tag name to remove
name: String,
},
/// Compute the composefs image object id of the rootfs of a stored OCI image
ComputeId {
#[clap(flatten)]
config_opts: OCIConfigFilesystemOptions,
},
/// Create the composefs image of the rootfs of a stored OCI image, commit it to the repo, and print its image object ID
CreateImage {
#[clap(flatten)]
config_opts: OCIConfigFilesystemOptions,
/// optional reference name for the image, use as 'ref/<name>' elsewhere
#[clap(long)]
image_name: Option<String>,
},
/// Seal a stored OCI image by creating a cloned manifest with embedded verity digest (a.k.a. composefs image object ID)
/// in the repo, then prints the stream and verity digest of the new sealed manifest
Seal {
#[clap(flatten)]
config_opts: OCIConfigOptions,
},
/// Mounts a stored and sealed OCI image by looking up its composefs image. Note that the composefs image must be built
/// and committed to the repo first
Mount {
/// the name of the target OCI manifest stream, either a stream ID in format oci-config-<hash_type>:<hash_digest> or a reference in 'ref/'
name: String,
/// the mountpoint
mountpoint: String,
},
/// Create the composefs image of the rootfs of a stored OCI image, perform bootable transformation, commit it to the repo,
/// then configure boot for the image by writing new boot resources and bootloader entries to boot partition. Performs
/// state preparation for composefs-setup-root consumption as well. Note that state preparation here is not suitable for
/// consumption by bootc.
PrepareBoot {
#[clap(flatten)]
config_opts: OCIConfigOptions,
/// boot partition mount point
#[clap(long, default_value = "/boot")]
bootdir: PathBuf,
/// Boot entry identifier to use. By default uses ID provided by the image or kernel version
#[clap(long)]
entry_id: Option<String>,
/// additional kernel command line
#[clap(long)]
cmdline: Vec<String>,
},
}
/// Common options for reading a filesystem from a path
#[derive(Debug, Parser)]
struct FsReadOptions {
/// The path to the filesystem
path: PathBuf,
/// Transform the filesystem for boot (SELinux labels, empty /boot and /sysroot)
#[clap(long)]
bootable: bool,
/// Don't copy /usr metadata to root directory (use if root already has well-defined metadata)
#[clap(long)]
no_propagate_usr_to_root: bool,
}
#[derive(Debug, Subcommand)]
enum Command {
/// Take a transaction lock on the repository.
/// This prevents garbage collection from occurring.
Transaction,
/// Reconstitutes a split stream and writes it to stdout
Cat {
/// the name of the stream to cat, either a content identifier or prefixed with 'ref/'
name: String,
},
/// Perform garbage collection
GC {
/// Additional roots to keep (image or stream names)
#[clap(long, short = 'r')]
root: Vec<String>,
/// Preview what would be deleted without actually deleting
#[clap(long, short = 'n')]
dry_run: bool,
},
/// Imports a composefs image (unsafe!)
ImportImage { reference: String },
/// Commands for dealing with OCI images and layers
#[cfg(feature = "oci")]
Oci {
#[clap(subcommand)]
cmd: OciCommand,
},
/// Mounts a composefs image, possibly enforcing fsverity of the image
Mount {
/// the name of the image to mount, either an fs-verity hash or prefixed with 'ref/'
name: String,
/// the mountpoint
mountpoint: String,
},
/// Read rootfs located at a path, add all files to the repo, then create the composefs image of the rootfs,
/// commit it to the repo, and print its image object ID
CreateImage {
#[clap(flatten)]
fs_opts: FsReadOptions,
/// optional reference name for the image, use as 'ref/<name>' elsewhere
image_name: Option<String>,
},
/// Read rootfs located at a path, add all files to the repo, then compute the composefs image object id of the rootfs.
/// Note that this does not create or commit the composefs image itself.
ComputeId {
#[clap(flatten)]
fs_opts: FsReadOptions,
},
/// Read rootfs located at a path, add all files to the repo, then dump full content of the rootfs to a composefs dumpfile
/// and write to stdout.
CreateDumpfile {
#[clap(flatten)]
fs_opts: FsReadOptions,
},
/// Lists all object IDs referenced by an image
ImageObjects {
/// the name of the image to read, either an object ID digest or prefixed with 'ref/'
name: String,
},
#[cfg(feature = "http")]
Fetch { url: String, name: String },
}
fn verity_opt<ObjectID>(opt: &Option<String>) -> Result<Option<ObjectID>>
where
ObjectID: FsVerityHashValue,
{
Ok(match opt {
Some(value) => Some(FsVerityHashValue::from_hex(value)?),
None => None,
})
}
fn open_repo<ObjectID>(args: &App) -> Result<Repository<ObjectID>>
where
ObjectID: FsVerityHashValue,
{
let mut repo = (if let Some(path) = &args.repo {
Repository::open_path(CWD, path)
} else if args.system {
Repository::open_system()
} else if args.user {
Repository::open_user()
} else if rustix::process::getuid().is_root() {
Repository::open_system()
} else {
Repository::open_user()
})?;
repo.set_insecure(args.insecure);
Ok(repo)
}
#[tokio::main]
async fn main() -> Result<()> {
env_logger::init();
let args = App::parse();
match args.hash {
HashType::Sha256 => run_cmd_with_repo(open_repo::<Sha256HashValue>(&args)?, args).await,
HashType::Sha512 => run_cmd_with_repo(open_repo::<Sha512HashValue>(&args)?, args).await,
}
}
async fn run_cmd_with_repo<ObjectID>(repo: Repository<ObjectID>, args: App) -> Result<()>
where
ObjectID: FsVerityHashValue,
{
match args.cmd {
Command::Transaction => {
// just wait for ^C
loop {
std::thread::park();
}
}
Command::Cat { name } => {
repo.merge_splitstream(&name, None, None, &mut std::io::stdout())?;
}
Command::ImportImage { reference } => {
let image_id = repo.import_image(&reference, &mut std::io::stdin())?;
println!("{}", image_id.to_id());
}
#[cfg(feature = "oci")]
Command::Oci { cmd: oci_cmd } => match oci_cmd {
OciCommand::ImportLayer { name, digest } => {
let object_id = composefs_oci::import_layer(
&Arc::new(repo),
&digest,
name.as_deref(),
&mut std::io::stdin(),
)?;
println!("{}", object_id.to_id());
}
OciCommand::ImportImageSplitfdstream {
socket,
image_id,
tag,
} => {
let result = composefs_oci::import_complete_image_from_splitfdstream(
&Arc::new(repo),
&socket,
&image_id,
tag.as_deref(),
)?;
println!("Imported complete image:");
println!(" Manifest: {}", result.manifest_digest);
println!(" Config: {}", result.config_digest);
println!(" Layers: {}", result.layers_imported);
println!(" Size: {} bytes", result.total_size_bytes);
if let Some(tag_name) = tag {
println!(" Tagged: {}", tag_name);
}
}
OciCommand::LsLayer { name } => {
composefs_oci::ls_layer(&repo, &name)?;
}
OciCommand::Dump {
config_opts:
OCIConfigFilesystemOptions {
base_config:
OCIConfigOptions {
ref config_name,
ref config_verity,
},
bootable,
},
} => {
let verity = verity_opt(config_verity)?;
let mut fs =
composefs_oci::image::create_filesystem(&repo, config_name, verity.as_ref())?;
if bootable {
fs.transform_for_boot(&repo)?;
}
fs.print_dumpfile()?;
}
OciCommand::ComputeId {
config_opts:
OCIConfigFilesystemOptions {
base_config:
OCIConfigOptions {
ref config_name,
ref config_verity,
},
bootable,
},
} => {
let verity = verity_opt(config_verity)?;
let mut fs =
composefs_oci::image::create_filesystem(&repo, config_name, verity.as_ref())?;
if bootable {
fs.transform_for_boot(&repo)?;
}
let id = fs.compute_image_id();
println!("{}", id.to_hex());
}
OciCommand::CreateImage {
config_opts:
OCIConfigFilesystemOptions {
base_config:
OCIConfigOptions {
ref config_name,
ref config_verity,
},
bootable,
},
ref image_name,
} => {
let verity = verity_opt(config_verity)?;
let mut fs =
composefs_oci::image::create_filesystem(&repo, config_name, verity.as_ref())?;
if bootable {
fs.transform_for_boot(&repo)?;
}
let image_id = fs.commit_image(&repo, image_name.as_deref())?;
println!("{}", image_id.to_id());
}
OciCommand::Pull { ref image, name } => {
// If no explicit name provided, use the image reference as the tag
let tag_name = name.as_deref().unwrap_or(image);
let result =
composefs_oci::pull_image(&Arc::new(repo), image, Some(tag_name), None).await?;
println!("manifest {}", result.manifest_digest);
println!("config {}", result.config_digest);
println!("verity {}", result.manifest_verity.to_hex());
println!("tagged {tag_name}");
}
OciCommand::ListImages => {
let images = composefs_oci::oci_image::list_images(&repo)?;
if images.is_empty() {
println!("No images found");
} else {
println!(
"{:<30} {:<12} {:<10} {:<8} {:<6}",
"NAME", "DIGEST", "ARCH", "SEALED", "LAYERS"
);
for img in images {
let digest_short = img
.manifest_digest
.strip_prefix("sha256:")
.unwrap_or(&img.manifest_digest);
let digest_display = if digest_short.len() > 12 {
&digest_short[..12]
} else {
digest_short
};
println!(
"{:<30} {:<12} {:<10} {:<8} {:<6}",
img.name,
digest_display,
if img.architecture.is_empty() {
"artifact"
} else {
&img.architecture
},
if img.sealed { "yes" } else { "no" },
img.layer_count
);
}
}
}
OciCommand::Inspect { ref image } => {
let img = if image.starts_with("sha256:") {
composefs_oci::oci_image::OciImage::open(&repo, image, None)?
} else {
composefs_oci::oci_image::OciImage::open_ref(&repo, image)?
};
println!("Manifest: {}", img.manifest_digest());
println!("Config: {}", img.config_digest());
println!(
"Type: {}",
if img.is_container_image() {
"container"
} else {
"artifact"
}
);
if img.is_container_image() {
println!("Architecture: {}", img.architecture());
println!("OS: {}", img.os());
}
if let Some(created) = img.created() {
println!("Created: {created}");
}
println!(
"Sealed: {}",
if img.is_sealed() { "yes" } else { "no" }
);
if let Some(seal) = img.seal_digest() {
println!("Seal digest: {seal}");
}
println!("Layers: {}", img.layer_descriptors().len());
for (i, layer) in img.layer_descriptors().iter().enumerate() {
println!(" [{i}] {} ({} bytes)", layer.digest(), layer.size());
}
if let Some(labels) = img.labels() {
if !labels.is_empty() {
println!("Labels:");
for (k, v) in labels {
println!(" {k}: {v}");
}
}
}
}
OciCommand::Tag {
ref manifest_digest,
ref name,
} => {
composefs_oci::oci_image::tag_image(&repo, manifest_digest, name)?;
println!("Tagged {manifest_digest} as {name}");
}
OciCommand::Untag { ref name } => {
composefs_oci::oci_image::untag_image(&repo, name)?;
println!("Removed tag {name}");
}
OciCommand::Seal {
config_opts:
OCIConfigOptions {
ref config_name,
ref config_verity,
},
} => {
let verity = verity_opt(config_verity)?;
let (digest, verity) =
composefs_oci::seal(&Arc::new(repo), config_name, verity.as_ref())?;
println!("config {digest}");
println!("verity {}", verity.to_id());
}
OciCommand::Mount {
ref name,
ref mountpoint,
} => {
composefs_oci::mount(&repo, name, mountpoint, None)?;
}
OciCommand::PrepareBoot {
config_opts:
OCIConfigOptions {
ref config_name,
ref config_verity,
},
ref bootdir,
ref entry_id,
ref cmdline,
} => {
let verity = verity_opt(config_verity)?;
let mut fs =
composefs_oci::image::create_filesystem(&repo, config_name, verity.as_ref())?;
let entries = fs.transform_for_boot(&repo)?;
let id = fs.commit_image(&repo, None)?;
let Some(entry) = entries.into_iter().next() else {
anyhow::bail!("No boot entries!");
};
let cmdline_refs: Vec<&str> = cmdline.iter().map(String::as_str).collect();
write_boot::write_boot_simple(
&repo,
entry,
&id,
args.insecure,
bootdir,
None,
entry_id.as_deref(),
&cmdline_refs,
)?;
let state = args
.repo
.as_ref()
.map(|p: &PathBuf| p.parent().unwrap())
.unwrap_or(Path::new("/sysroot"))
.join("state/deploy")
.join(id.to_hex());
create_dir_all(state.join("var"))?;
create_dir_all(state.join("etc/upper"))?;
create_dir_all(state.join("etc/work"))?;
}
},
Command::ComputeId { fs_opts } => {
let mut fs = if fs_opts.no_propagate_usr_to_root {
composefs::fs::read_filesystem(CWD, &fs_opts.path, Some(&repo))?
} else {
composefs::fs::read_container_root(CWD, &fs_opts.path, Some(&repo))?
};
if fs_opts.bootable {
fs.transform_for_boot(&repo)?;
}
let id = fs.compute_image_id();
println!("{}", id.to_hex());
}
Command::CreateImage {
fs_opts,
ref image_name,
} => {
let mut fs = if fs_opts.no_propagate_usr_to_root {
composefs::fs::read_filesystem(CWD, &fs_opts.path, Some(&repo))?
} else {
composefs::fs::read_container_root(CWD, &fs_opts.path, Some(&repo))?
};
if fs_opts.bootable {
fs.transform_for_boot(&repo)?;
}
let id = fs.commit_image(&repo, image_name.as_deref())?;
println!("{}", id.to_id());
}
Command::CreateDumpfile { fs_opts } => {
let mut fs = if fs_opts.no_propagate_usr_to_root {
composefs::fs::read_filesystem(CWD, &fs_opts.path, Some(&repo))?
} else {
composefs::fs::read_container_root(CWD, &fs_opts.path, Some(&repo))?
};
if fs_opts.bootable {
fs.transform_for_boot(&repo)?;
}
fs.print_dumpfile()?;
}
Command::Mount { name, mountpoint } => {
repo.mount_at(&name, &mountpoint)?;
}
Command::ImageObjects { name } => {
let objects = repo.objects_for_image(&name)?;
for object in objects {
println!("{}", object.to_id());
}
}
Command::GC { root, dry_run } => {
let roots: Vec<&str> = root.iter().map(|s| s.as_str()).collect();
let result = if dry_run {
repo.gc_dry_run(&roots)?
} else {
repo.gc(&roots)?
};
if dry_run {
println!("Dry run (no files deleted):");
}
println!(
"Objects: {} removed ({} bytes)",
result.objects_removed, result.objects_bytes
);
if result.images_pruned > 0 || result.streams_pruned > 0 {
println!(
"Pruned symlinks: {} images, {} streams",
result.images_pruned, result.streams_pruned
);
}
}
#[cfg(feature = "http")]
Command::Fetch { url, name } => {
let (digest, verity) = composefs_http::download(&url, &name, Arc::new(repo)).await?;
println!("content {digest}");
println!("verity {}", verity.to_hex());
}
}
Ok(())
}