easy_fuser 0.4.5

A flexible and idiomatic Fuse implementation for Rust
Documentation
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
use std::{
    ffi::{OsStr, OsString},
    fmt::Debug,
    hash::Hash,
    path::PathBuf,
    sync::{Arc, atomic::Ordering},
};

use std::sync::{RwLock, atomic::AtomicU64};

use crate::{inode_mapper, types::*};
use crate::{inode_mapper::InodeMapper, inode_multi_mapper::*};

pub(crate) const ROOT_INO: u64 = 1;

/// Trait to allow a FileIdType to be mapped to use a converter
pub trait InodeResolvable {
    type Resolver: FileIdResolver<ResolvedType = Self>;

    fn create_resolver() -> Self::Resolver;
}

impl InodeResolvable for PathBuf {
    type Resolver = PathResolver;

    fn create_resolver() -> Self::Resolver {
        PathResolver::new()
    }
}

impl InodeResolvable for Inode {
    type Resolver = InodeResolver;

    fn create_resolver() -> Self::Resolver {
        InodeResolver::new()
    }
}

impl InodeResolvable for Vec<OsString> {
    type Resolver = ComponentsResolver;

    fn create_resolver() -> Self::Resolver {
        ComponentsResolver::new()
    }
}

impl<BackingId> InodeResolvable for HybridId<BackingId>
where
    BackingId: Clone + Eq + Hash + Send + Sync + Debug + 'static,
{
    type Resolver = HybridResolver<BackingId>;

    fn create_resolver() -> Self::Resolver {
        HybridResolver::new()
    }
}

/// FileIdResolver
/// FileIdResolver handles its data behind Locks if needed and should not be nested inside a Mutex
pub trait FileIdResolver: Send + Sync + 'static {
    type ResolvedType: FileIdType;

    fn new() -> Self;
    fn resolve_id(&self, ino: u64) -> Self::ResolvedType;
    fn lookup(
        &self,
        parent: u64,
        child: &OsStr,
        id: <Self::ResolvedType as FileIdType>::_Id,
        increment: bool,
    ) -> u64;
    fn add_children(
        &self,
        parent: u64,
        children: Vec<(OsString, <Self::ResolvedType as FileIdType>::_Id)>,
        increment: bool,
    ) -> Vec<(OsString, u64)>;
    fn forget(&self, ino: u64, nlookup: u64);
    fn rename(&self, parent: u64, name: &OsStr, newparent: u64, newname: &OsStr);
}

pub struct InodeResolver {}

impl FileIdResolver for InodeResolver {
    type ResolvedType = Inode;

    fn new() -> Self {
        Self {}
    }

    fn resolve_id(&self, ino: u64) -> Self::ResolvedType {
        Inode::from(ino)
    }

    fn lookup(&self, _parent: u64, _child: &OsStr, id: Inode, _increment: bool) -> u64 {
        id.into()
    }

    // Do nothing, user should provide its own inode
    fn add_children(
        &self,
        _parent: u64,
        children: Vec<(OsString, Inode)>,
        _increment: bool,
    ) -> Vec<(OsString, u64)> {
        children
            .into_iter()
            .map(|(name, inode)| (name, u64::from(inode)))
            .collect()
    }

    fn forget(&self, _ino: u64, _nlookup: u64) {}

    fn rename(&self, _parent: u64, _name: &OsStr, _newparent: u64, _newname: &OsStr) {}
}

pub struct ComponentsResolver {
    mapper: RwLock<InodeMapper<AtomicU64>>,
}

impl FileIdResolver for ComponentsResolver {
    type ResolvedType = Vec<OsString>;

    fn new() -> Self {
        ComponentsResolver {
            mapper: RwLock::new(InodeMapper::new(AtomicU64::new(0))),
        }
    }

    fn resolve_id(&self, ino: u64) -> Self::ResolvedType {
        self.mapper
            .read()
            .unwrap()
            .resolve(&Inode::from(ino))
            .expect("Failed to resolve inode")
            .iter()
            .map(|inode_info| (**inode_info.name).clone())
            .collect()
    }

    fn lookup(&self, parent: u64, child: &OsStr, _id: (), increment: bool) -> u64 {
        let parent = Inode::from(parent);
        {
            // Optimistically assume the child exists
            if let Some(lookup_result) = self.mapper.read().unwrap().lookup(&parent, child) {
                if increment {
                    lookup_result.data.fetch_add(1, Ordering::SeqCst);
                }
                return u64::from(lookup_result.inode.clone());
            }
        }
        // This scenario happens if the child node does not exist or the backing ID does not match
        u64::from(
            self.mapper
                .write()
                .expect("Failed to acquire write lock")
                .insert_child(&parent, child.to_os_string(), |_| {
                    // If the child node already exists, use the existing reference count
                    AtomicU64::new(if increment { 1 } else { 0 })
                })
                .expect("Failed to insert child"),
        )
    }

    fn add_children(
        &self,
        parent: u64,
        children: Vec<(OsString, ())>,
        increment: bool,
    ) -> Vec<(OsString, u64)> {
        let value_creator =
            |value_creator: inode_mapper::ValueCreatorParams<AtomicU64>| match value_creator
                .existing_data
            {
                Some(nlookup) => {
                    let count = nlookup.load(Ordering::Relaxed);
                    AtomicU64::new(if increment { count + 1 } else { count })
                }
                None => AtomicU64::new(if increment { 1 } else { 0 }),
            };
        let children_with_creator: Vec<_> = children
            .iter()
            .map(|(name, _)| (name.clone(), value_creator))
            .collect();
        let parent_inode = Inode::from(parent);
        let inserted_children = self
            .mapper
            .write()
            .expect("Failed to acquire write lock")
            .insert_children(&parent_inode, children_with_creator)
            .expect("Failed to insert children");
        inserted_children
            .into_iter()
            .zip(children)
            .map(|(inode, (name, _))| (name, u64::from(inode)))
            .collect()
    }

    fn forget(&self, ino: u64, nlookup: u64) {
        let inode = Inode::from(ino);
        {
            // Optimistically assume we don't have to remove yet
            let guard = self.mapper.read().expect("Failed to acquire read lock");
            let inode_info = guard.get(&inode).expect("Failed to find inode");
            if inode_info.data.fetch_sub(nlookup, Ordering::SeqCst) > 0 {
                return;
            }
        }
        self.mapper.write().unwrap().remove(&inode).unwrap();
    }

    fn rename(&self, parent: u64, name: &OsStr, newparent: u64, newname: &OsStr) {
        let parent_inode = Inode::from(parent);
        let newparent_inode = Inode::from(newparent);
        self.mapper
            .write()
            .expect("Failed to acquire write lock")
            .rename(
                &parent_inode,
                name,
                &newparent_inode,
                newname.to_os_string(),
            )
            .expect("Failed to rename inode");
    }
}

pub struct PathResolver {
    resolver: ComponentsResolver,
}

impl FileIdResolver for PathResolver {
    type ResolvedType = PathBuf;

    fn new() -> Self {
        PathResolver {
            resolver: ComponentsResolver::new(),
        }
    }

    fn resolve_id(&self, ino: u64) -> Self::ResolvedType {
        self.resolver
            .resolve_id(ino)
            .iter()
            .rev()
            .collect::<PathBuf>()
    }

    fn lookup(
        &self,
        parent: u64,
        child: &OsStr,
        id: <Self::ResolvedType as FileIdType>::_Id,
        increment: bool,
    ) -> u64 {
        self.resolver.lookup(parent, child, id, increment)
    }

    fn add_children(
        &self,
        parent: u64,
        children: Vec<(OsString, <Self::ResolvedType as FileIdType>::_Id)>,
        increment: bool,
    ) -> Vec<(OsString, u64)> {
        self.resolver.add_children(parent, children, increment)
    }

    fn forget(&self, ino: u64, nlookup: u64) {
        self.resolver.forget(ino, nlookup);
    }

    fn rename(&self, parent: u64, name: &OsStr, newparent: u64, newname: &OsStr) {
        self.resolver.rename(parent, name, newparent, newname);
    }
}

pub struct HybridResolver<BackingId>
where
    BackingId: Clone + Eq + Hash,
{
    mapper: Arc<RwLock<InodeMultiMapper<AtomicU64, BackingId>>>,
}

impl<BackingId> FileIdResolver for HybridResolver<BackingId>
where
    BackingId: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static,
{
    type ResolvedType = HybridId<BackingId>;

    fn new() -> Self {
        let instance = Arc::new(RwLock::new(InodeMultiMapper::new(AtomicU64::new(0))));
        HybridResolver { mapper: instance }
    }

    fn resolve_id(&self, ino: u64) -> Self::ResolvedType {
        HybridId::new(Inode::from(ino), self.mapper.clone())
    }

    fn lookup(
        &self,
        parent: u64,
        child: &OsStr,
        id: <Self::ResolvedType as FileIdType>::_Id,
        increment: bool,
    ) -> u64 {
        let parent = Inode::from(parent);
        {
            // Optimistically assume the child exists
            if let Some(lookup_result) = self
                .mapper
                .read()
                .expect("cannot acquire read lock")
                .lookup(&parent, child)
            {
                // Backing ID must match to use the hot path
                if lookup_result.backing_id.cloned() == id {
                    if increment {
                        lookup_result.data.fetch_add(1, Ordering::SeqCst);
                    }
                    return u64::from(lookup_result.inode.clone());
                }
            }
        }
        // This scenario happens if the child node does not exist or the backing ID does not match
        u64::from(
            self.mapper
                .write()
                .expect("Failed to acquire write lock")
                .insert_child(&parent, child.to_os_string(), id, |params| {
                    // If the child node already exists, use the existing reference count
                    let mut new_value = params
                        .existing_data
                        .map(|d| d.load(Ordering::SeqCst))
                        .unwrap_or(0);
                    if increment {
                        new_value += 1;
                    }
                    AtomicU64::new(new_value)
                })
                .expect("Failed to insert child"),
        )
    }

    fn add_children(
        &self,
        parent: u64,
        children: Vec<(OsString, <Self::ResolvedType as FileIdType>::_Id)>,
        increment: bool,
    ) -> Vec<(OsString, u64)> {
        let value_creator =
            |value_creator: ValueCreatorParams<AtomicU64>| match value_creator.existing_data {
                Some(nlookup) => {
                    let count = nlookup.load(Ordering::Relaxed);
                    AtomicU64::new(if increment { count + 1 } else { count })
                }
                None => AtomicU64::new(if increment { 1 } else { 0 }),
            };
        let children_with_creator: Vec<_> = children
            .iter()
            .map(|(name, id)| (name.clone(), id.clone(), value_creator))
            .collect();
        let parent_inode = Inode::from(parent);
        let inserted_children = self
            .mapper
            .write()
            .expect("Failed to acquire write lock")
            .insert_children(&parent_inode, children_with_creator)
            .expect("Failed to insert children");
        inserted_children
            .into_iter()
            .zip(children)
            .map(|(inode, (name, _))| (name, u64::from(inode)))
            .collect()
    }

    fn forget(&self, ino: u64, nlookup: u64) {
        let inode = Inode::from(ino);
        {
            // Optimistically assume we don't have to remove yet
            let guard = self.mapper.read().expect("Failed to acquire read lock");
            let inode_info = guard.get(&inode).expect("Failed to find inode");
            if inode_info.data.fetch_sub(nlookup, Ordering::SeqCst) > 0 {
                return;
            }
        }
        self.mapper
            .write()
            .expect("Failed to acquire write lock")
            .remove(&inode)
            .unwrap();
    }

    fn rename(&self, parent: u64, name: &OsStr, newparent: u64, newname: &OsStr) {
        let parent_inode = Inode::from(parent);
        let newparent_inode = Inode::from(newparent);
        self.mapper
            .write()
            .expect("Failed to acquire write lock")
            .rename(
                &parent_inode,
                name,
                &newparent_inode,
                newname.to_os_string(),
            )
            .expect("Failed to rename inode");
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::ffi::OsStr;
    use std::path::PathBuf;

    #[test]
    fn test_components_resolver() {
        let resolver = ComponentsResolver::new();

        // Test lookup and resolve_id
        let parent_ino = ROOT_INODE.into();
        let child_ino = resolver.lookup(parent_ino, OsStr::new("child"), (), true);
        let resolved_path = resolver.resolve_id(child_ino);

        assert_eq!(resolved_path, vec![OsString::from("child")]);

        // Test add_children
        let grandchildren = vec![
            (OsString::from("grandchild1"), ()),
            (OsString::from("grandchild2"), ()),
        ];
        let added_children = resolver.add_children(child_ino, grandchildren, true);

        assert_eq!(added_children.len(), 2);

        // Test forget
        resolver.forget(child_ino, 1);

        // Test rename
        resolver.rename(
            parent_ino,
            OsStr::new("child"),
            parent_ino,
            OsStr::new("renamed_child"),
        );

        let renamed_path = resolver.resolve_id(child_ino);
        assert_eq!(renamed_path, vec![OsString::from("renamed_child")]);
    }

    #[test]
    fn test_path_resolver() {
        let resolver = PathResolver::new();

        // Test lookup and resolve_id for root
        let root_ino = ROOT_INODE.into();
        let root_path = resolver.resolve_id(root_ino);
        assert_eq!(root_path, PathBuf::from(""));

        // Create a nested structure: /dir1/dir2/file.txt
        let dir1_ino = resolver.lookup(root_ino, OsStr::new("dir1"), (), true);
        let dir2_ino = resolver.lookup(dir1_ino, OsStr::new("dir2"), (), true);
        let file_ino = resolver.lookup(dir2_ino, OsStr::new("file.txt"), (), true);

        // Test resolve_id for nested structure
        let file_path = resolver.resolve_id(file_ino);
        assert_eq!(file_path, PathBuf::from("dir1/dir2/file.txt"));

        // Test add_children
        let dir2_children = vec![
            (OsString::from("child1.txt"), ()),
            (OsString::from("child2.txt"), ()),
        ];
        let added_children = resolver.add_children(dir2_ino, dir2_children, true);
        assert_eq!(added_children.len(), 2);

        // Verify added children
        for (name, ino) in added_children {
            let child_path = resolver.resolve_id(ino);
            assert_eq!(
                child_path,
                PathBuf::from(format!("dir1/dir2/{}", name.to_str().unwrap()))
            );
        }

        // Test forget
        resolver.forget(file_ino, 1);

        // Test rename within the same directory
        resolver.rename(
            dir2_ino,
            OsStr::new("file.txt"),
            dir2_ino,
            OsStr::new("renamed_file.txt"),
        );

        let renamed_file_path = resolver.resolve_id(file_ino);
        assert_eq!(
            renamed_file_path,
            PathBuf::from("dir1/dir2/renamed_file.txt")
        );

        // Test rename to a different directory
        let dir3_ino = resolver.lookup(root_ino, OsStr::new("dir3"), (), true);
        resolver.rename(
            dir2_ino,
            OsStr::new("renamed_file.txt"),
            dir3_ino,
            OsStr::new("moved_file.txt"),
        );

        let moved_file_path = resolver.resolve_id(file_ino);
        assert_eq!(moved_file_path, PathBuf::from("dir3/moved_file.txt"));

        // Test lookup for non-existent file
        let non_existent_ino = resolver.lookup(root_ino, OsStr::new("non_existent"), (), false);
        assert_ne!(non_existent_ino, 0);
        let non_existent_path = resolver.resolve_id(non_existent_ino);
        assert_eq!(non_existent_path, PathBuf::from("non_existent"));
    }

    #[test]
    fn test_hybrid_resolver() {
        let resolver = HybridResolver::<u64>::new();

        // Test lookup and resolve_id for root
        let root_ino = ROOT_INODE.into();
        let root_id = resolver.resolve_id(root_ino);
        assert_eq!(root_id.first_path(), Some(PathBuf::from("")));

        // Test lookup and resolve_id for child and create nested structures
        let dir1_ino = resolver.lookup(root_ino, OsStr::new("dir1"), Some(1), true);
        let dir1_id = resolver.resolve_id(dir1_ino);
        assert_eq!(dir1_id.first_path(), Some(PathBuf::from("dir1")));

        let dir2_ino = resolver.lookup(dir1_ino, OsStr::new("dir2"), Some(2), true);
        let dir2_id = resolver.resolve_id(dir2_ino);
        assert_eq!(dir2_id.first_path(), Some(PathBuf::from("dir1/dir2")));

        // Test add_children
        let grandchildren = vec![
            (OsString::from("grandchild1"), Some(3)),
            (OsString::from("grandchild2"), Some(4)),
        ];
        let added_grandchildren = resolver.add_children(dir2_ino, grandchildren, true);
        assert_eq!(added_grandchildren.len(), 2);
        for (name, ino) in added_grandchildren.iter() {
            let child_path = resolver.resolve_id(*ino);
            assert_eq!(
                child_path.first_path(),
                Some(PathBuf::from("dir1/dir2").join(name))
            );
        }

        // Test forget
        resolver.forget(added_grandchildren[0].1, 1);

        // Test rename within the same directory
        resolver.rename(
            dir2_ino,
            OsStr::new("grandchild2"),
            dir2_ino,
            OsStr::new("grandchild2_renamed"),
        );
        let renamed_grandchild_path = resolver.resolve_id(added_grandchildren[1].1);
        assert_eq!(
            renamed_grandchild_path.first_path(),
            Some(PathBuf::from("dir1/dir2/grandchild2_renamed"))
        );

        // Test rename to a different directory
        let dir3_ino = resolver.lookup(root_ino, OsStr::new("dir3"), Some(5), true);
        resolver.rename(
            dir2_ino,
            OsStr::new("grandchild2_renamed"),
            dir3_ino,
            OsStr::new("grandchild2_renamed"),
        );
        let renamed_grandchild_path = resolver.resolve_id(added_grandchildren[1].1);
        assert_eq!(
            renamed_grandchild_path.first_path(),
            Some(PathBuf::from("dir3/grandchild2_renamed"))
        );

        // Test lookup for non-existent file
        let non_existent_ino =
            resolver.lookup(root_ino, OsStr::new("non_existent"), Some(6), false);
        assert_ne!(non_existent_ino, 0);
        let non_existent_path = resolver.resolve_id(non_existent_ino);
        assert_eq!(
            non_existent_path.first_path(),
            Some(PathBuf::from("non_existent"))
        );

        // Test lookup for a file with existing backing ID
        let hard_link_ino = resolver.lookup(root_ino, OsStr::new("hard_link"), Some(7), true);
        let hard_link_id = resolver.resolve_id(hard_link_ino);
        assert_eq!(hard_link_id.first_path(), Some(PathBuf::from("hard_link")));

        let hard_link_ino_2 = resolver.lookup(dir2_ino, OsStr::new("hard_linked"), Some(7), true);
        let hard_link_id_2 = resolver.resolve_id(hard_link_ino_2);
        assert_eq!(
            hard_link_ino_2, hard_link_ino,
            "hard link should be the same if callers supply the same ID"
        );

        resolver.lookup(dir1_ino, OsStr::new("hard_linked_2"), Some(7), true);
        let paths = hard_link_id_2.all_paths(Some(100));
        assert!(paths.contains(&PathBuf::from("dir1/dir2/hard_linked")));
        assert!(paths.contains(&PathBuf::from("hard_link")));
        assert!(paths.contains(&PathBuf::from("dir1/hard_linked_2")));

        // Overriding a location with a new backing ID should always create a new inode
        let overridden_hard_link_ino =
            resolver.lookup(dir2_ino, OsStr::new("hard_linked"), Some(8), true);
        assert_ne!(
            overridden_hard_link_ino, hard_link_ino,
            "overridden location's inode should change upon encountering a new ID"
        );

        // Test path resolution after overriding a location with a new backing ID
        let paths = hard_link_id_2.all_paths(Some(100));
        assert!(
            !paths.contains(&PathBuf::from("dir1/dir2/hard_linked")),
            "the path list should no longer contain the overridden location"
        );
        assert!(paths.contains(&PathBuf::from("hard_link")));
        assert!(paths.contains(&PathBuf::from("dir1/hard_linked_2")));
    }

    #[test]
    fn test_path_resolver_back_and_forth_rename() {
        let resolver = PathResolver::new();

        // Test lookup and resolve_id for root
        let root_ino = ROOT_INODE.into();
        let root_path = resolver.resolve_id(root_ino);
        assert_eq!(root_path, PathBuf::from(""));

        // Add directories
        let dir1_ino = resolver.lookup(root_ino, OsStr::new("dir1"), (), true);
        let dir2_ino = resolver.lookup(dir1_ino, OsStr::new("dir2"), (), true);
        let file_ino = resolver.lookup(root_ino, OsStr::new("file.txt"), (), true);

        // Rename file to a different directory
        resolver.rename(
            root_ino,
            OsStr::new("file.txt"),
            dir2_ino,
            OsStr::new("file.txt"),
        );
        let renamed_file_path = resolver.resolve_id(file_ino);
        assert_eq!(renamed_file_path, PathBuf::from("dir1/dir2/file.txt"));

        // Rename file back to original directory
        resolver.rename(
            dir2_ino,
            OsStr::new("file.txt"),
            root_ino,
            OsStr::new("file.txt"),
        );
        let renamed_file_path = resolver.resolve_id(file_ino);
        assert_eq!(renamed_file_path, PathBuf::from("file.txt"));
    }
}