-
Notifications
You must be signed in to change notification settings - Fork 203
/
main.rs
2101 lines (1982 loc) · 81.6 KB
/
main.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
// Copyright 2020 Ant Group. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0
#![deny(warnings)]
#[macro_use(crate_authors)]
extern crate clap;
#[macro_use]
extern crate anyhow;
#[macro_use]
extern crate log;
#[macro_use]
extern crate serde_json;
#[macro_use]
extern crate lazy_static;
use crate::deduplicate::{
check_bootstrap_versions_consistency, update_ctx_from_parent_bootstrap, Deduplicate,
SqliteDatabase,
};
use std::convert::TryFrom;
use std::fs::{self, metadata, DirEntry, File, OpenOptions};
use std::os::unix::fs::FileTypeExt;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use anyhow::{bail, Context, Result};
use clap::parser::ValueSource;
use clap::{Arg, ArgAction, ArgMatches, Command as App};
use nix::unistd::{getegid, geteuid};
use nydus::{get_build_time_info, setup_logging};
use nydus_api::{BuildTimeInfo, ConfigV2, LocalFsConfig};
use nydus_builder::{
parse_chunk_dict_arg, ArtifactStorage, BlobCacheGenerator, BlobCompactor, BlobManager,
BootstrapManager, BuildContext, BuildOutput, Builder, ChunkdictBlobInfo, ChunkdictChunkInfo,
ConversionType, DirectoryBuilder, Feature, Features, Generator, HashChunkDict, Merger,
Prefetch, PrefetchPolicy, StargzBuilder, TarballBuilder, WhiteoutSpec,
};
use nydus_rafs::metadata::{MergeError, RafsSuper, RafsSuperConfig, RafsVersion};
use nydus_storage::backend::localfs::LocalFs;
use nydus_storage::backend::BlobBackend;
use nydus_storage::device::BlobFeatures;
use nydus_storage::factory::BlobFactory;
use nydus_storage::meta::{format_blob_features, BatchContextGenerator};
use nydus_storage::{RAFS_DEFAULT_CHUNK_SIZE, RAFS_MAX_CHUNK_SIZE};
use nydus_utils::trace::{EventTracerClass, TimingTracerClass, TraceClass};
use nydus_utils::{
compress, digest, event_tracer, lazy_drop, register_tracer, root_tracer, timing_tracer,
};
use serde::{Deserialize, Serialize};
use crate::unpack::{OCIUnpacker, Unpacker};
use crate::validator::Validator;
#[cfg(target_os = "linux")]
use nydus_service::ServiceArgs;
#[cfg(target_os = "linux")]
use std::str::FromStr;
mod deduplicate;
mod inspect;
mod stat;
mod unpack;
mod validator;
const BLOB_ID_MAXIMUM_LENGTH: usize = 255;
#[derive(Serialize, Deserialize, Default)]
pub struct OutputSerializer {
/// The binary version of builder (nydus-image).
version: String,
/// RAFS meta data file path.
bootstrap: String,
/// Represents all blob in blob table ordered by blob index, this field
/// only include the layer that does have a blob, and should be deprecated
/// in future, use `artifacts` field to replace.
blobs: Vec<String>,
/// Performance trace info for current build.
trace: serde_json::Map<String, serde_json::Value>,
/// RAFS filesystem version (5 or 6).
fs_version: String,
/// Chunk compression algorithm.
compressor: String,
}
impl OutputSerializer {
fn dump(
matches: &ArgMatches,
build_output: BuildOutput,
build_info: &BuildTimeInfo,
compressor: compress::Algorithm,
fs_version: RafsVersion,
) -> Result<()> {
let output_json: Option<PathBuf> = matches
.get_one::<String>("output-json")
.map(|o| o.to_string().into());
if let Some(ref f) = output_json {
let w = OpenOptions::new()
.truncate(true)
.create(true)
.write(true)
.open(f)
.with_context(|| format!("can not open output file {}", f.display()))?;
let trace = root_tracer!().dump_summary_map().unwrap_or_default();
let version = format!("{}-{}", build_info.package_ver, build_info.git_commit);
let output = Self {
version,
bootstrap: build_output.bootstrap_path.unwrap_or_default(),
blobs: build_output.blobs,
trace,
fs_version: fs_version.to_string(),
compressor: compressor.to_string(),
};
serde_json::to_writer_pretty(w, &output)
.context("failed to write result to output file")?;
}
Ok(())
}
fn dump_for_check(
matches: &ArgMatches,
build_info: &BuildTimeInfo,
blob_ids: Vec<String>,
bootstrap: &Path,
compressor: compress::Algorithm,
fs_version: RafsVersion,
) -> Result<()> {
let output_json: Option<PathBuf> = matches
.get_one::<String>("output-json")
.map(|o| o.to_string().into());
if let Some(ref f) = output_json {
let w = OpenOptions::new()
.truncate(true)
.create(true)
.write(true)
.open(f)
.with_context(|| format!("can not open output file {}", f.display()))?;
let trace = root_tracer!().dump_summary_map().unwrap_or_default();
let version = format!("{}-{}", build_info.package_ver, build_info.git_commit);
let output = Self {
version,
bootstrap: bootstrap.display().to_string(),
blobs: blob_ids,
trace,
fs_version: fs_version.to_string(),
compressor: compressor.to_string(),
};
serde_json::to_writer(w, &output).context("failed to write result to output file")?;
}
Ok(())
}
}
fn prepare_cmd_args(bti_string: &'static str) -> App {
let arg_chunk_dict = Arg::new("chunk-dict")
.long("chunk-dict")
.help("File path of chunk dictionary for data deduplication");
let arg_prefetch_policy = Arg::new("prefetch-policy")
.long("prefetch-policy")
.help("Set data prefetch policy")
.required(false)
.default_value("none")
.value_parser(["fs", "blob", "none"]);
let arg_output_json = Arg::new("output-json")
.long("output-json")
.short('J')
.help("File path to save operation result in JSON format");
let arg_config = Arg::new("config")
.long("config")
.short('C')
.help("Configuration file for storage backend, cache and RAFS FUSE filesystem.")
.required(false);
let app = App::new("")
.version(bti_string)
.author(crate_authors!())
.about("Build, analyze, inspect or validate RAFS filesystems/Nydus accelerated container images")
.arg(
Arg::new("log-file")
.long("log-file")
.short('L')
.help("Log file path")
.required(false)
.global(true),
)
.arg(
Arg::new("log-level")
.long("log-level")
.short('l')
.help("Log level:")
.default_value("info")
.value_parser(["trace", "debug", "info", "warn", "error"])
.required(false)
.global(true),
);
let app = app.subcommand(
App::new("create")
.about("Create RAFS filesystems from directories, tar files or OCI images")
.arg(
Arg::new("SOURCE")
.help("source from which to build the RAFS filesystem")
.required(true)
.num_args(1),
)
.arg(
Arg::new("type")
.long("type")
.short('t')
.alias("source-type")
.help("Conversion type:")
.default_value("dir-rafs")
.value_parser([
"directory",
"dir-rafs",
"estargz-rafs",
"estargz-ref",
"estargztoc-ref",
"tar-rafs",
"tar-tarfs",
"targz-rafs",
"targz-ref",
"stargz_index",
])
)
.arg(
Arg::new("bootstrap")
.long("bootstrap")
.short('B')
.help("File path to save the generated RAFS metadata blob")
.required_unless_present_any(["blob-dir", "blob-inline-meta"])
.conflicts_with("blob-inline-meta"),
)
.arg(
Arg::new("blob-dir")
.long("blob-dir")
.short('D')
.help("Directory path to save generated RAFS metadata and data blobs"),
)
.arg(
Arg::new("blob")
.long("blob")
.short('b')
.help("File path to save the generated RAFS data blob")
.required_unless_present_any(["type", "blob-dir"]),
)
.arg(
Arg::new("blob-inline-meta")
.long("blob-inline-meta")
.alias("inline-bootstrap")
.help("Inline RAFS metadata and blob metadata into the data blob")
.action(ArgAction::SetTrue)
.conflicts_with("blob-id")
.required(false),
)
.arg(
Arg::new("blob-id")
.long("blob-id")
.required_if_eq_any([("type", "estargztoc-ref"), ("type", "stargz_index")])
.help("OSS object id for the generated RAFS data blob")
)
.arg(
Arg::new("blob-data-size")
.long("blob-data-size")
.help("Set data blob size for 'estargztoc-ref' conversion"),
)
.arg(
Arg::new("blob-offset")
.long("blob-offset")
.help("File offset to store RAFS data, to support storing data blobs into tar files")
.hide(true)
.default_value("0"),
)
.arg(
Arg::new("chunk-size")
.long("chunk-size")
.help("Set the size of data chunks, must be power of two and between 0x1000-0x1000000:")
.required(false),
)
.arg(
Arg::new("batch-size")
.long("batch-size")
.help("Set the batch size to merge small chunks, must be power of two, between 0x1000-0x1000000 or be zero:")
.required(false)
.default_value("0"),
)
.arg(
Arg::new("compressor")
.long("compressor")
.help("Algorithm to compress data chunks:")
.required(false)
.default_value("zstd")
.value_parser(["none", "lz4_block", "zstd"]),
)
.arg(
Arg::new("digester")
.long("digester")
.help("Algorithm to digest data chunks:")
.required(false)
.default_value("blake3")
.value_parser(["blake3", "sha256"]),
)
.arg( arg_config.clone() )
.arg(
Arg::new("fs-version")
.long("fs-version")
.short('v')
.help("Set RAFS format version number:")
.default_value("6")
.value_parser(["5", "6"]),
)
.arg(
Arg::new("features")
.long("features")
.value_parser(["blob-toc"])
.help("Enable/disable features")
)
.arg(
arg_chunk_dict.clone(),
)
.arg(
Arg::new("parent-bootstrap")
.long("parent-bootstrap")
.help("File path of the parent/referenced RAFS metadata blob (optional)")
.required(false),
)
.arg(
Arg::new("aligned-chunk")
.long("aligned-chunk")
.help("Align uncompressed data chunks to 4K, only for RAFS V5")
.action(ArgAction::SetTrue)
)
.arg(
Arg::new("repeatable")
.long("repeatable")
.help("Generate reproducible RAFS metadata")
.action(ArgAction::SetTrue)
.required(false),
)
.arg(
Arg::new("disable-check")
.long("disable-check")
.help("Disable RAFS metadata validation after build")
.hide(true)
.action(ArgAction::SetTrue)
.required(false)
)
.arg(
Arg::new("whiteout-spec")
.long("whiteout-spec")
.help("Set the type of whiteout specification:")
.default_value("oci")
.value_parser(["oci", "overlayfs", "none"])
)
.arg(
arg_prefetch_policy.clone(),
)
.arg(
arg_output_json.clone(),
)
.arg(
Arg::new("encrypt")
.long("encrypt")
.short('E')
.help("Encrypt the generated RAFS metadata and data blobs")
.action(ArgAction::SetTrue)
.required(false)
)
.arg(
Arg::new("blob-cache-dir")
.long("blob-cache-dir")
.help("Directory path to generate blob cache files ($id.blob.meta and $id.blob.data)")
.value_parser(clap::value_parser!(PathBuf))
.conflicts_with("blob-inline-meta")
.conflicts_with("blob")
.conflicts_with("blob-dir")
.conflicts_with("compressor")
.required(false)
)
);
let app = app.subcommand(
App::new("chunkdict")
.about("deduplicate RAFS filesystem metadata")
.subcommand(
App::new("generate")
.about("generate chunk dictionary based on database")
.arg(
Arg::new("database")
.long("database")
.help("Database connection address for assisting chunk dictionary generation, e.g. /path/database.db")
.default_value("sqlite:///home/runner/output/database.db")
.required(false),
)
.arg(
Arg::new("bootstrap")
.long("bootstrap")
.short('B')
.help("Output path of nydus overlaid bootstrap"),
)
.arg(
Arg::new("blob-dir")
.long("blob-dir")
.short('D')
.help("Directory path to save generated RAFS metadata and data blobs"),
)
.arg(arg_prefetch_policy.clone())
.arg(arg_output_json.clone())
.arg(arg_config.clone())
.arg(
Arg::new("SOURCE")
.help("bootstrap paths (allow one or more)")
.required(true)
.num_args(1..),
)
.arg(
Arg::new("verbose")
.long("verbose")
.short('v')
.help("Output message in verbose mode")
.action(ArgAction::SetTrue)
.required(false),
)
)
);
let app = app.subcommand(
App::new("merge")
.about("Merge multiple bootstraps into a overlaid bootstrap")
.arg(
Arg::new("parent-bootstrap")
.long("parent-bootstrap")
.help("File path of the parent/referenced RAFS metadata blob (optional)")
.required(false),
)
.arg(
Arg::new("bootstrap")
.long("bootstrap")
.short('B')
.help("Output path of nydus overlaid bootstrap"),
)
.arg(
Arg::new("blob-dir")
.long("blob-dir")
.short('D')
.help("Directory path to save generated RAFS metadata and data blobs"),
)
.arg(arg_chunk_dict.clone())
.arg(arg_prefetch_policy)
.arg(arg_output_json.clone())
.arg(
Arg::new("blob-digests")
.long("blob-digests")
.required(false)
.help("RAFS blob digest list separated by comma"),
)
.arg(
Arg::new("original-blob-ids")
.long("original-blob-ids")
.required(false)
.help("original blob id list separated by comma, it may usually be a sha256 hex string"),
)
.arg(
Arg::new("blob-sizes")
.long("blob-sizes")
.required(false)
.help("RAFS blob size list separated by comma"),
)
.arg(
Arg::new("blob-toc-digests")
.long("blob-toc-digests")
.required(false)
.help("RAFS blob toc digest list separated by comma"),
)
.arg(
Arg::new("blob-toc-sizes")
.long("blob-toc-sizes")
.required(false)
.help("RAFS blob toc size list separated by comma"),
)
.arg(arg_config.clone())
.arg(
Arg::new("SOURCE")
.help("bootstrap paths (allow one or more)")
.required(true)
.num_args(1..),
),
);
let app = app.subcommand(
App::new("check")
.about("Validate RAFS filesystem metadata")
.arg(
Arg::new("BOOTSTRAP")
.help("File path of RAFS metadata")
.required_unless_present("bootstrap"),
)
.arg(
Arg::new("bootstrap")
.short('B')
.long("bootstrap")
.help("[Deprecated] File path of RAFS meta blob/bootstrap")
.conflicts_with("BOOTSTRAP")
.required(false),
)
.arg(
Arg::new("blob-dir")
.long("blob-dir")
.short('D')
.conflicts_with("config")
.help(
"Directory for localfs storage backend, hosting data blobs and cache files",
),
)
.arg(arg_config.clone())
.arg(
Arg::new("verbose")
.long("verbose")
.short('v')
.help("Output message in verbose mode")
.action(ArgAction::SetTrue)
.required(false),
)
.arg(arg_output_json.clone()),
);
#[cfg(target_os = "linux")]
let app = app.subcommand(
App::new("export")
.about("Export RAFS filesystems as raw block disk images or tar files")
.arg(
Arg::new("block")
.long("block")
.action(ArgAction::SetTrue)
.required(true)
.help("Export RAFS filesystems as raw block disk images")
)
.arg(
Arg::new("bootstrap")
.long("bootstrap")
.short('B')
.help("Bootstrap of the RAFS filesystem to be exported")
.requires("localfs-dir")
)
.arg(Arg::new("config")
.long("config")
.short('C')
.help("Configuration file containing a `BlobCacheEntry` object")
.required(false))
.arg(
Arg::new("localfs-dir")
.long("localfs-dir")
.short('D')
.help(
"Path to the `localfs` working directory, which also enables the `localfs` storage backend"
)
.requires("bootstrap")
.conflicts_with("config"),
)
.arg(
Arg::new("threads")
.long("threads")
.default_value("4")
.help("Number of worker threads to execute export operation, valid values: [1-32]")
.value_parser(Command::thread_validator)
.required(false),
)
.arg(
Arg::new("output")
.long("output")
.short('O')
.help("File path for saving the exported content")
.required_unless_present("localfs-dir")
)
.arg(
Arg::new("verity")
.long("verity")
.help("Generate dm-verity data for block device")
.action(ArgAction::SetTrue)
.required(false)
.requires("block")
)
);
let app = app.subcommand(
App::new("inspect")
.about("Inspect RAFS filesystem metadata in interactive or request mode")
.arg(
Arg::new("BOOTSTRAP")
.help("File path of RAFS metadata")
.required_unless_present("bootstrap"),
)
.arg(
Arg::new("bootstrap")
.short('B')
.long("bootstrap")
.help("[Deprecated] File path of RAFS meta blob/bootstrap")
.conflicts_with("BOOTSTRAP")
.required(false),
)
.arg(
Arg::new("blob-dir")
.long("blob-dir")
.short('D')
.conflicts_with("config")
.help(
"Directory for localfs storage backend, hosting data blobs and cache files",
),
)
.arg(arg_config.clone())
.arg(
Arg::new("request")
.long("request")
.short('R')
.help("Inspect RAFS filesystem metadata in request mode")
.required(false),
),
);
let app = app.subcommand(
App::new("stat")
.about("Generate statistics information for RAFS filesystems")
.arg(
Arg::new("bootstrap")
.long("bootstrap")
.short('B')
.help("Generate statistics information for the RAFS filesystem")
.required(false),
)
.arg(
Arg::new("blob-dir")
.long("blob-dir")
.short('D')
.help("Generate statistics information for all RAFS filesystems in the directory")
.required(false),
)
.arg(
Arg::new("target")
.long("target")
.short('T')
.help("Generate statistics information for the RAFS filesystem after applying chunk deduplication")
.required(false),
)
.arg(arg_config.clone())
.arg(
Arg::new("digester")
.long("digester")
.help("Algorithm to digest data chunks:")
.required(false)
.default_value("blake3")
.value_parser(["blake3", "sha256"]),
)
.arg(
arg_output_json.clone(),
)
);
let app = app.subcommand(
App::new("compact")
.about("(experimental)Compact specific nydus image, remove unused chunks in blobs, merge small blobs")
.arg(
Arg::new("bootstrap")
.long("bootstrap")
.short('B')
.help("bootstrap to compact")
.required(true),
)
.arg(
Arg::new("backend-type")
.long("backend-type")
.help(format!(
"Type of backend [possible values: {}]",
BlobFactory::supported_backends()
.into_iter()
.filter(|x| x != "localfs")
.collect::<Vec<_>>()
.join(", ")
))
.required(false)
.group("backend"),
)
.arg(
Arg::new("backend-config")
.long("backend-config")
.help("Config string of backend")
.required(false),
)
.arg(
Arg::new("backend-config-file")
.long("backend-config-file")
.help("Config file of backend")
.conflicts_with("backend-config")
.required(false),
)
.arg(
Arg::new("blob")
.long("blob")
.short('b')
.help("Path to RAFS data blob file")
.required(false)
.group("backend"),
)
.arg(
Arg::new("blob-dir")
.long("blob-dir")
.short('D')
.help(
"Directory for localfs storage backend, hosting data blobs and cache files",
)
.group("backend"),
)
.arg( arg_chunk_dict )
.arg(
Arg::new("output-bootstrap")
.long("output-bootstrap")
.short('O')
.help("bootstrap to output, default is source bootstrap add suffix .compact"),
)
.arg(
arg_output_json,
)
.group(
clap::ArgGroup::new("backend")
.args(&["backend-type", "blob", "blob-dir"])
.required(false),
),
);
app.subcommand(
App::new("unpack")
.about("Unpack a RAFS filesystem to a tar file")
.arg(
Arg::new("BOOTSTRAP")
.help("File path of RAFS metadata")
.required_unless_present("bootstrap"),
)
.arg(
Arg::new("backend-type")
.long("backend-type")
.help(format!(
"Type of backend [possible values: {}]",
BlobFactory::supported_backends()
.into_iter()
.filter(|x| x != "localfs")
.collect::<Vec<_>>()
.join(", ")
))
.required(false)
.group("backend"),
)
.arg(
Arg::new("backend-config")
.long("backend-config")
.help("Config string of backend")
.required(false),
)
.arg(
Arg::new("backend-config-file")
.long("backend-config-file")
.help("Config file of backend")
.conflicts_with("backend-config")
.required(false),
)
.arg(
Arg::new("bootstrap")
.short('B')
.long("bootstrap")
.help("[Deprecated] File path of RAFS meta blob/bootstrap")
.conflicts_with("BOOTSTRAP")
.required(false),
)
.arg(
Arg::new("blob")
.long("blob")
.short('b')
.help("Path to RAFS data blob file")
.required(false)
.group("backend"),
)
.arg(
Arg::new("blob-dir")
.long("blob-dir")
.short('D')
.help(
"Directory for localfs storage backend, hosting data blobs and cache files",
)
.group("backend"),
)
.arg(
Arg::new("output")
.long("output")
.help("Path for output tar file")
.required(true),
)
.group(
clap::ArgGroup::new("backend")
.args(&["backend-type", "blob", "blob-dir"])
.required(false),
),
)
}
fn init_log(matches: &ArgMatches) -> Result<()> {
let mut log_file = None;
if let Some(file) = matches.get_one::<String>("log-file") {
let path = PathBuf::from(file);
log_file = Some(path);
}
// Safe to unwrap because it has a default value and possible values are defined.
let level = matches
.get_one::<String>("log-level")
.unwrap()
.parse()
.unwrap();
setup_logging(log_file, level, 0).context("failed to setup logging")
}
lazy_static! {
static ref BTI_STRING: String = get_build_time_info().0;
static ref BTI: BuildTimeInfo = get_build_time_info().1;
}
fn main() -> Result<()> {
let build_info = BTI.to_owned();
let mut app = prepare_cmd_args(BTI_STRING.as_str());
let usage = app.render_usage();
let cmd = app.get_matches();
init_log(&cmd)?;
register_tracer!(TraceClass::Timing, TimingTracerClass);
register_tracer!(TraceClass::Event, EventTracerClass);
if let Some(matches) = cmd.subcommand_matches("create") {
Command::create(matches, &build_info)
} else if let Some(matches) = cmd.subcommand_matches("chunkdict") {
match matches.subcommand_name() {
Some("generate") => Command::chunkdict_generate(
matches.subcommand_matches("generate").unwrap(),
&build_info,
),
_ => {
println!("{}", usage);
Ok(())
}
}
} else if let Some(matches) = cmd.subcommand_matches("merge") {
let result = Command::merge(matches, &build_info);
if let Err(ref err) = result {
if let Some(MergeError::InconsistentFilesystem(_)) = err.downcast_ref::<MergeError>() {
error!("message:{}", err);
std::process::exit(2);
}
}
result
} else if let Some(matches) = cmd.subcommand_matches("check") {
Command::check(matches, &build_info)
} else if let Some(matches) = cmd.subcommand_matches("inspect") {
Command::inspect(matches)
} else if let Some(matches) = cmd.subcommand_matches("stat") {
Command::stat(matches)
} else if let Some(matches) = cmd.subcommand_matches("compact") {
Command::compact(matches, &build_info)
} else if let Some(matches) = cmd.subcommand_matches("unpack") {
Command::unpack(matches)
} else {
#[cfg(target_os = "linux")]
if let Some(matches) = cmd.subcommand_matches("export") {
Command::export(&cmd, matches, &build_info)
} else {
println!("{}", usage);
Ok(())
}
#[cfg(not(target_os = "linux"))]
{
println!("{}", usage);
Ok(())
}
}
}
struct Command {}
impl Command {
fn create(matches: &ArgMatches, build_info: &BuildTimeInfo) -> Result<()> {
let blob_id = Self::get_blob_id(matches)?;
let blob_offset = Self::get_blob_offset(matches)?;
let parent_path = Self::get_parent_bootstrap(matches)?;
let prefetch = Self::get_prefetch(matches)?;
let source_path = PathBuf::from(matches.get_one::<String>("SOURCE").unwrap());
let conversion_type: ConversionType = matches.get_one::<String>("type").unwrap().parse()?;
let blob_inline_meta = matches.get_flag("blob-inline-meta");
let repeatable = matches.get_flag("repeatable");
let version = Self::get_fs_version(matches)?;
let chunk_size = Self::get_chunk_size(matches, conversion_type)?;
let batch_size = Self::get_batch_size(matches, version, conversion_type, chunk_size)?;
let blob_cache_storage = Self::get_blob_cache_storage(matches, conversion_type)?;
// blob-cache-dir and blob-dir/blob are a set of mutually exclusive functions,
// the former is used to generate blob cache, nydusd is directly started through blob cache,
// the latter is to generate nydus blob, as nydusd backend to start
let blob_storage = if blob_cache_storage.is_some() {
None
} else {
Self::get_blob_storage(matches, conversion_type)?
};
let aligned_chunk = if version.is_v6() && conversion_type != ConversionType::TarToTarfs {
true
} else {
// get_fs_version makes sure it's either v6 or v5.
matches.get_flag("aligned-chunk")
};
let whiteout_spec: WhiteoutSpec = matches
.get_one::<String>("whiteout-spec")
.map(|s| s.as_str())
.unwrap_or_default()
.parse()?;
let mut compressor = matches
.get_one::<String>("compressor")
.map(|s| s.as_str())
.unwrap_or_default()
.parse()?;
let mut digester = matches
.get_one::<String>("digester")
.map(|s| s.as_str())
.unwrap_or_default()
.parse()?;
let blob_data_size = Self::get_blob_size(matches, conversion_type)?;
let features = Features::try_from(
matches
.get_one::<String>("features")
.map(|s| s.as_str())
.unwrap_or_default(),
)?;
let encrypt = matches.get_flag("encrypt");
match conversion_type {
ConversionType::DirectoryToRafs => {
Self::ensure_directory(&source_path)?;
if blob_storage.is_none() && blob_cache_storage.is_none() {
bail!("both --blob and --blob-dir or --blob-cache-dir are missing");
}
}
ConversionType::EStargzToRafs
| ConversionType::TargzToRafs
| ConversionType::TarToRafs => {
Self::ensure_file(&source_path)?;
if blob_storage.is_none() && blob_cache_storage.is_none() {
bail!("both --blob and --blob-dir or --blob-cache-dir are missing");
}
}
ConversionType::TarToRef
| ConversionType::TargzToRef
| ConversionType::EStargzToRef => {
Self::ensure_file(&source_path)?;
if matches.value_source("compressor") != Some(ValueSource::DefaultValue)
&& compressor != compress::Algorithm::GZip
{
info!(
"only GZip is supported for conversion type {}, use GZip instead of {}",
conversion_type, compressor
);
}
if matches.value_source("digester") != Some(ValueSource::DefaultValue)
&& digester != digest::Algorithm::Sha256
{
info!(
"only SHA256 is supported for conversion type {}, use SHA256 instead of {}",
conversion_type, compressor
);
}
compressor = compress::Algorithm::GZip;
digester = digest::Algorithm::Sha256;
if blob_storage.is_none() && blob_cache_storage.is_none() {
bail!("all of --blob, --blob-dir and --blob-cache-dir are missing");
} else if !prefetch.disabled && prefetch.policy == PrefetchPolicy::Blob {
bail!(
"conversion type {} conflicts with '--prefetch-policy blob'",
conversion_type
);
}
if version != RafsVersion::V6 {
bail!(
"'--fs-version 5' conflicts with conversion type '{}', only V6 is supported",
conversion_type
);
}
if blob_id.trim() != "" {
bail!(
"conversion type '{}' conflicts with '--blob-id'",
conversion_type
);
}
if encrypt {