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
use crate::error::DockerArchiveError;
use crate::Result;
use itertools::Itertools;
use path_clean::clean;
use serde::Serialize;
use std::cell::RefCell;
use std::rc::{Rc, Weak};
use std::{collections::HashMap, io::Read};
use tar::{Archive, EntryType};
use uuid::Uuid;
use xxhash_rust::xxh3::xxh3_64;
const WHITEOUT_PREFIX: &'static str = ".wh.";
const DOUBLE_WHITEOUT_PREFIX: &'static str = ".wh..wh..";
mod uuid_serde {
use std::str::FromStr;
use serde::{de::Error, Deserialize, Deserializer, Serializer};
use uuid::Uuid;
pub fn serialize<S>(uuid: &Uuid, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&uuid.to_string())
}
#[allow(dead_code)]
pub fn deserialize<'de, D>(deserializer: D) -> Result<Uuid, D::Error>
where
D: Deserializer<'de>,
{
let s = <&str>::deserialize(deserializer)?;
Uuid::from_str(s).map_err(Error::custom)
}
}
#[derive(Debug, Default, Serialize)]
pub struct FileTree {
pub root: Rc<RefCell<FileNode>>,
pub size: u64,
pub file_size: u64,
pub name: String,
#[serde(with = "uuid_serde")]
pub id: Uuid,
}
struct CompareMark {
pub lower_node: Rc<RefCell<FileNode>>,
pub upper_node: Rc<RefCell<FileNode>>,
pub tentative: Option<DiffType>,
pub finalis: Option<DiffType>,
}
impl FileTree {
pub fn search<E>(tree: Rc<RefCell<Self>>, evaluator: &E) -> Vec<Rc<RefCell<FileNode>>>
where
E: Fn(&FileNode) -> bool,
{
let mut ret = vec![];
let root = Rc::clone(&tree.borrow().root);
FileNode::visit_depth_parent_first(
root,
&mut |node| {
ret.push(node);
},
evaluator,
);
ret
}
pub fn copy(tree: Rc<RefCell<Self>>) -> Rc<RefCell<Self>> {
let new_tree = Rc::new(RefCell::new(FileTree {
size: tree.borrow().size,
file_size: tree.borrow().file_size,
..Default::default()
}));
let new_tree_root = FileNode::copy(
Rc::clone(&tree.borrow().root),
Rc::clone(&new_tree.borrow().root),
);
FileNode::visit_depth_child_first(
Rc::clone(&new_tree_root),
&mut |node| {
node.borrow_mut().tree = Rc::downgrade(&new_tree);
},
&|_| true,
);
new_tree.borrow_mut().root = new_tree_root;
new_tree
}
pub fn stack_trees(trees: Vec<Rc<RefCell<FileTree>>>) -> Rc<RefCell<FileTree>> {
let tree = FileTree::copy(Rc::clone(&trees[0]));
for i in 1..trees.len() {
FileTree::stack(Rc::clone(&tree), Rc::clone(&trees[i]))
}
tree
}
pub fn stack(lower: Rc<RefCell<Self>>, upper: Rc<RefCell<Self>>) {
let upper_root = Rc::clone(&upper.borrow().root);
FileNode::visit_depth_child_first(
upper_root,
&mut |upper_node| {
let path = upper_node.borrow().path.clone();
if upper_node.borrow().is_whiteout() {
FileTree::remove_path(Rc::clone(&lower), &path);
return;
}
FileTree::add_path(
Rc::clone(&lower),
&path,
upper_node.borrow().data.file_info.clone(),
);
},
&|_| true,
);
}
pub fn compare_mark(lower: Rc<RefCell<Self>>, upper: Rc<RefCell<Self>>) {
let mut modifications = vec![];
FileNode::visit_depth_child_first(
Rc::clone(&upper.borrow().root),
&mut |upper_node| {
let path = upper_node.borrow().path.clone();
if upper_node.borrow().is_whiteout() {
if let Some(lower_node) = FileTree::get_node(Rc::clone(&lower), &path) {
FileNode::assign_diff_type(lower_node, DiffType::Removed);
}
return;
}
let lower_node = FileTree::get_node(Rc::clone(&lower), &path);
if lower_node.is_none() {
let (_, new_nodes) = FileTree::add_path(
Rc::clone(&lower),
&path,
upper_node.borrow().data.file_info.clone(),
);
for new_node in new_nodes.iter().rev() {
modifications.push(CompareMark {
lower_node: Rc::clone(new_node),
upper_node: Rc::clone(&upper_node),
tentative: None,
finalis: Some(DiffType::Added),
});
}
return;
}
let lower_node = lower_node.unwrap();
let diff_type =
FileNode::compare(Some(Rc::clone(&lower_node)), Some(Rc::clone(&upper_node)));
modifications.push(CompareMark {
lower_node: Rc::clone(&lower_node),
upper_node: Rc::clone(&upper_node),
tentative: Some(diff_type),
finalis: None,
})
},
&|_| true,
);
for pair in modifications.iter() {
if let Some(diff_type) = pair.finalis {
FileNode::assign_diff_type(Rc::clone(&pair.lower_node), diff_type);
} else {
let lower_node_diff_type = pair.lower_node.borrow().data.diff_type;
if lower_node_diff_type == DiffType::Unmodified {
FileNode::derive_diff_type(
Rc::clone(&pair.lower_node),
pair.tentative.unwrap(),
);
}
pair.lower_node.borrow_mut().data.file_info =
pair.upper_node.borrow().data.file_info.clone();
}
}
}
pub fn get_node(tree: Rc<RefCell<Self>>, path: &str) -> Option<Rc<RefCell<FileNode>>> {
let mut node = Rc::clone(&tree.borrow().root);
for name in path.trim_matches('/').split('/') {
if name.is_empty() {
continue;
}
let child = node.borrow().children.get(name).map(Rc::clone);
if child.is_none() {
return None;
} else {
node = child.unwrap();
}
}
Some(node)
}
pub fn add_path(
tree: Rc<RefCell<Self>>,
path: &str,
data: FileInfo,
) -> (Option<Rc<RefCell<FileNode>>>, Vec<Rc<RefCell<FileNode>>>) {
let mut added_nodes = vec![];
let path = clean(path);
if path.eq(".") {
return (None, added_nodes);
}
let mut node = Rc::clone(&tree.borrow().root);
for node_name in path.trim_matches('/').split('/') {
if node_name.is_empty() {
continue;
}
let child = node.borrow().children.get(node_name).map(Rc::clone);
if child.is_some() {
node = child.unwrap();
continue;
}
if node_name.starts_with(DOUBLE_WHITEOUT_PREFIX) {
return (None, added_nodes);
}
node = FileNode::add_child(Rc::clone(&node), node_name, Default::default());
added_nodes.push(Rc::clone(&node));
}
node.borrow_mut().data.file_info = data;
(Some(node), added_nodes)
}
pub fn remove_path(tree: Rc<RefCell<Self>>, path: &str) {
if let Some(node) = Self::get_node(tree, path) {
FileNode::remove(node);
}
}
pub fn build_from_layer_tar<R: Read>(ar: Archive<R>) -> Result<Rc<RefCell<Self>>> {
let tree = Rc::new(RefCell::new(FileTree::default()));
{
let a = tree.borrow();
let mut root = a.root.borrow_mut();
root.tree = Rc::downgrade(&tree);
}
let file_infos = FileInfo::get_file_infos(ar)?;
for file_info in file_infos.into_iter() {
let path = file_info.path.clone();
tree.borrow_mut().file_size += file_info.size;
FileTree::add_path(Rc::clone(&tree), &path, file_info);
}
tree.borrow().root.borrow_mut().path = "/".to_string();
Ok(tree)
}
}
#[derive(Debug, Default, Serialize)]
pub struct FileNode {
#[serde(skip)]
pub tree: Weak<RefCell<FileTree>>,
#[serde(skip)]
pub parent: Weak<RefCell<FileNode>>,
pub name: String,
pub data: NodeData,
pub children: HashMap<String, Rc<RefCell<FileNode>>>,
pub path: String,
}
impl FileNode {
pub fn copy(node: Rc<RefCell<Self>>, parent: Rc<RefCell<Self>>) -> Rc<RefCell<Self>> {
let new_node = Self {
tree: Weak::clone(&parent.borrow().tree),
parent: Rc::downgrade(&parent),
name: node.borrow().name.clone(),
data: node.borrow().data.clone(),
path: node.borrow().path.clone(),
..Default::default()
};
let new_node = Rc::new(RefCell::new(new_node));
for (name, child) in node.borrow().children.iter() {
let new_child = Self::copy(Rc::clone(child), Rc::clone(&new_node));
new_node
.borrow_mut()
.children
.insert(name.clone(), new_child);
}
new_node
}
pub fn derive_diff_type(node: Rc<RefCell<Self>>, diff_type: DiffType) {
let leaf = node.borrow().is_leaf();
if leaf {
return Self::assign_diff_type(node, diff_type);
}
let mut my_diff_type = diff_type;
for child in node.borrow().children.values() {
my_diff_type = my_diff_type.merge(child.borrow().data.diff_type);
}
return Self::assign_diff_type(node, my_diff_type);
}
pub fn assign_diff_type(node: Rc<RefCell<Self>>, diff_type: DiffType) {
node.borrow_mut().data.diff_type = diff_type;
if matches!(diff_type, DiffType::Removed) {
for child in node.borrow().children.values() {
FileNode::assign_diff_type(Rc::clone(child), diff_type);
}
}
}
pub fn add_child(parent: Rc<RefCell<Self>>, name: &str, data: FileInfo) -> Rc<RefCell<Self>> {
if let Some(node) = parent.borrow().children.get(name) {
node.borrow_mut().data.file_info = data;
return Rc::clone(node);
}
let mut path = parent.borrow().path.clone();
path.push('/');
if let Some(s) = name.strip_prefix(WHITEOUT_PREFIX) {
path.push_str(s);
} else {
path.push_str(name);
}
let child = Rc::new(RefCell::new(FileNode {
tree: Weak::clone(&parent.borrow().tree),
parent: Rc::downgrade(&parent),
name: name.to_string(),
data: NodeData {
file_info: data,
..Default::default()
},
path,
..Default::default()
}));
parent
.borrow_mut()
.children
.insert(name.to_string(), Rc::clone(&child));
if let Some(t) = parent.borrow().tree.upgrade() {
t.borrow_mut().size += 1;
}
child
}
pub fn remove(node: Rc<RefCell<Self>>) {
if let Some(tree) = node.borrow().tree.upgrade() {
if Rc::ptr_eq(&node, &tree.borrow().root) {
return;
}
tree.borrow_mut().size -= 1;
}
if let Some(parent) = node.borrow().parent.upgrade() {
parent.borrow_mut().children.remove(&node.borrow().name);
}
let childs: Vec<Rc<RefCell<Self>>> = node.borrow().children.values().cloned().collect();
for child in childs.into_iter() {
FileNode::remove(child);
}
}
pub fn is_whiteout(&self) -> bool {
self.name.starts_with(WHITEOUT_PREFIX)
}
pub fn is_leaf(&self) -> bool {
self.children.is_empty()
}
pub fn compare(lower: Option<Rc<RefCell<Self>>>, upper: Option<Rc<RefCell<Self>>>) -> DiffType {
if lower.is_none() && upper.is_none() {
return DiffType::Unmodified;
}
if lower.is_none() && upper.is_some() {
return DiffType::Added;
}
if lower.is_some() && upper.is_none() {
return DiffType::Removed;
}
let (lower, upper) = (lower.unwrap(), upper.unwrap());
if upper.borrow().is_whiteout() {
return DiffType::Removed;
}
if lower.borrow().name.ne(&upper.borrow().name) {
panic!("comparing mismatched nodes");
}
let file_info_diff = lower
.borrow()
.data
.file_info
.compare(&upper.borrow().data.file_info);
file_info_diff
}
pub fn visit_depth_child_first<V, E>(node: Rc<RefCell<Self>>, visitor: &mut V, evaluator: &E)
where
V: FnMut(Rc<RefCell<FileNode>>) -> (),
E: Fn(&FileNode) -> bool,
{
for (_, v) in node.borrow().children.iter().sorted_by_key(|x| x.0) {
let child = Rc::clone(v);
FileNode::visit_depth_child_first(child, visitor, evaluator);
}
if let Some(tree) = node.borrow().tree.upgrade() {
if Rc::ptr_eq(&node, &tree.borrow().root) {
return;
}
}
let visit = evaluator(&node.borrow());
if visit {
visitor(Rc::clone(&node))
}
}
pub fn visit_depth_parent_first<V, E>(node: Rc<RefCell<Self>>, visitor: &mut V, evaluator: &E)
where
V: FnMut(Rc<RefCell<FileNode>>) -> (),
E: Fn(&FileNode) -> bool,
{
if !evaluator(&node.borrow()) {
return;
}
let mut is_root = false;
if let Some(tree) = node.borrow().tree.upgrade() {
if Rc::ptr_eq(&node, &tree.borrow().root) {
is_root = true;
}
}
if !is_root {
visitor(Rc::clone(&node));
}
for (_, v) in node.borrow().children.iter().sorted_by_key(|x| x.0) {
let child = Rc::clone(v);
FileNode::visit_depth_parent_first(child, visitor, evaluator);
}
}
}
#[derive(Debug, Default, Serialize, Clone)]
pub struct NodeData {
pub view_info: ViewInfo,
pub file_info: FileInfo,
pub diff_type: DiffType,
}
#[derive(Debug, Default, Serialize, Clone)]
pub struct ViewInfo {
pub collapsed: bool,
pub hidden: bool,
}
#[derive(Debug, Default, Serialize, Clone)]
pub struct FileInfo {
pub path: String,
pub type_flag: u8,
pub linkname: String,
pub hash: u64,
pub size: u64,
pub mode: u32,
pub uid: u64,
pub gid: u64,
pub is_dir: bool,
}
impl FileInfo {
pub fn get_file_infos<R: Read>(mut ar: Archive<R>) -> Result<Vec<Self>> {
let mut ret = vec![];
for entry in ar.entries()? {
let mut e = entry?;
if let Some(path) = e.path()?.to_str().map(clean) {
if path.eq(".") {
continue;
}
match e.header().entry_type() {
EntryType::XGlobalHeader | EntryType::XHeader => {
return Err(DockerArchiveError::InvalidArchiveX(format!(
"unexptected tar file: type={:?} name={}",
e.header().entry_type(),
&path,
)));
}
_ => {
let mut hash = 0;
if !e.header().entry_type().is_dir() {
let mut data = vec![];
e.read_to_end(&mut data)?;
hash = xxh3_64(data.as_slice());
}
ret.push(FileInfo {
path,
hash,
..e.header().into()
});
}
}
}
}
Ok(ret)
}
pub fn compare(&self, other: &Self) -> DiffType {
if self.type_flag == other.type_flag {
if self.hash == other.hash
&& self.mode == other.mode
&& self.uid == other.uid
&& self.gid == other.gid
{
return DiffType::Unmodified;
}
}
DiffType::Modified
}
}
impl From<&tar::Header> for FileInfo {
fn from(header: &tar::Header) -> Self {
Self {
path: header
.path()
.map(|p| p.to_str().unwrap_or("").to_string())
.unwrap_or(String::new()),
type_flag: header.entry_type().as_byte(),
linkname: header
.link_name()
.map(|p| {
p.map(|s| s.to_str().unwrap_or("").to_string())
.unwrap_or(String::new())
})
.unwrap_or(String::new()),
size: header.size().unwrap_or(0),
mode: header.mode().unwrap_or(0),
uid: header.uid().unwrap_or(0),
gid: header.gid().unwrap_or(0),
is_dir: header.entry_type().is_dir(),
..Default::default()
}
}
}
#[derive(Debug, Serialize, Clone, Copy, PartialEq)]
pub enum DiffType {
Unmodified,
Modified,
Added,
Removed,
}
impl Default for DiffType {
fn default() -> Self {
Self::Unmodified
}
}
impl DiffType {
pub fn merge(self, other: Self) -> DiffType {
if self.eq(&other) {
return self;
}
return Self::Modified;
}
}