btrfs-backup 0.2.2

A program for backup & restoration of btrfs subvolumes.
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
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
// Copyright (C) 2022-2024 Daniel Mueller <deso@posteo.net>
// SPDX-License-Identifier: GPL-3.0-or-later

use std::collections::BTreeSet;
use std::ffi::OsStr;
use std::ops::Deref as _;
use std::path::Path;
use std::path::PathBuf;
use std::rc::Rc;

use anyhow::bail;
use anyhow::Context as _;
use anyhow::Result;

use time::Duration;

use crate::btrfs::Btrfs;
use crate::ops::FileOps;
use crate::ops::LocalOps;
use crate::snapshot::current_time;
use crate::snapshot::Snapshot;
use crate::snapshot::SnapshotBase;
use crate::snapshot::Subvol;


/// Check if a given directory represents the root of a btrfs file
/// system.
fn is_root(btrfs: &Btrfs, directory: &Path) -> Result<bool> {
  btrfs.is_btrfs(directory)
}

/// Find the root of a btrfs file system based on a path pointing
/// somewhere into it.
///
/// # Notes
/// This function may produce false positives, i.e., it may report a
/// btrfs root not actually for the file system that `directory` is on.
/// That is because we have no knowledge of mount points and so if
/// `directory` lies on a non-btrfs file system but it is mounted within
/// a btrfs file system, we actually end up detecting the btrfs file
/// system's root.
fn find_root(btrfs: &Btrfs, directory: &Path) -> Result<PathBuf> {
  let mut to_check = directory;
  loop {
    if is_root(btrfs, to_check)? {
      return Ok(to_check.to_path_buf())
    }

    if let Some(parent) = to_check.parent() {
      to_check = parent
    } else {
      break
    }
  }

  bail!(
    "failed to find btrfs file system containing {}",
    directory.display()
  )
}


/// Find the most recent snapshot of a subvolume.
///
/// If `tag` is `None` then the snapshot's tag is ignored.
///
/// Please note that in the presence of differing tags, it is possible
/// for this function to not actually return the absolutely most-recent
/// snapshot, if two (or more) snapshots were created at the exact same
/// time but with different tags, one with more up-to-date content than
/// the other, they are considered equally up-to-date but, crucially,
/// NOT distinguished by a number, and which one is reported depends on
/// the lexicographical ordering of the tag. In practice it should be
/// outstandingly rare to hit this case.
fn find_most_recent_snapshot<'snaps>(
  snapshots: &'snaps [(Snapshot, usize)],
  subvol: &Path,
  tag: Option<&str>,
) -> Result<Option<&'snaps (Snapshot, usize)>> {
  let base_name = SnapshotBase::from_subvol_path(subvol)?;
  let snapshots = snapshots
    .iter()
    .filter(|(snapshot, _generation)| {
      snapshot.as_base_name() == base_name && (tag.is_none() || Some(snapshot.tag.as_ref()) == tag)
    })
    .collect::<Vec<_>>();

  // The most recent snapshot (i.e., the one with the largest time
  // stamp) will be the last one.
  Ok(snapshots.into_iter().last())
}


/// "Deploy" a snapshot in a source repository to a destination.
fn deploy(src: &Repo, dst: &Repo, src_snap: &Snapshot) -> Result<()> {
  let base_name = src_snap.as_base_name();
  let dst_snaps = dst
    .snapshots()?
    .into_iter()
    .map(|(snapshot, _generation)| snapshot)
    .filter(|snapshot| snapshot.as_base_name() == base_name)
    .collect::<BTreeSet<_>>();

  // Check whether the snapshot already exists at the destination. That
  // may be the case if the subvolume did not change and we did not
  // actually create a new snapshot to begin with.
  if dst_snaps.contains(src_snap) {
    return Ok(())
  }

  // TODO: The `src.snapshot` invocation above already retrieves the
  //       snapshot list internally. We should remove duplicate
  //       operations.
  let src_snaps = src
    .snapshots()?
    .into_iter()
    .map(|(snapshot, _generation)| snapshot)
    .filter(|snapshot| snapshot.as_base_name() == base_name)
    .collect::<BTreeSet<_>>();

  // Find all candidate parent snapshots, which is basically nothing
  // more than the set of snapshots of the provided subvolume available
  // in both repositories.
  let parents = src_snaps
    .intersection(&dst_snaps)
    .map(|snapshot| src.path().join(snapshot.to_string()))
    .collect::<Vec<_>>();
  let parents = parents.iter().map(OsStr::new);

  let () = src.btrfs.sync(&src.btrfs_root)?;
  let () = src.btrfs.send_recv(
    &src.path().join(src_snap.to_string()),
    parents,
    &dst.btrfs,
    &dst.path(),
  )?;

  Ok(())
}


/// Backup a subvolume from a source repository to a destination.
pub fn backup(src: &Repo, dst: &Repo, subvol: &Path, tag: &str) -> Result<Snapshot> {
  let src_snap = src.snapshot(subvol, tag)?;
  let () = deploy(src, dst, &src_snap)?;
  Ok(src_snap)
}


/// Restore a subvolume from a source repository.
pub fn restore(src: &Repo, dst: &Repo, subvol: &Path, snapshot_only: bool) -> Result<()> {
  if let Some(parent) = subvol.parent() {
    // The subvolume is unlikely to exist (after all, it's meant to be
    // restored). However, given that the user wants to restore it we
    // should make sure that the path to it exists.
    let () = dst.file_ops.create_dir_all(parent)?;
  }

  let snapshots = src.snapshots()?;
  // Note that for restoration purposes we always ignore the tag: we
  // always restore from the most up-to-date snapshot.
  let (snapshot, _generation) =
    find_most_recent_snapshot(&snapshots, subvol, None)?.with_context(|| {
      // In case the given source repository does not contain any snapshots
      // for the given subvolume we cannot do anything but signal that to
      // the user.
      format!(
        "No snapshot to restore found for subvolume {} in {}",
        subvol.display(),
        src.path().display()
      )
    })?;

  // We want to signal an error to the user in case the subvolume
  // already exists but he/she has asked us to restore it. We cannot
  // solely rely on btrfs snapshot for this detection because in case
  // there is a directory where 'subvolume' points to, the command will
  // just manifest the new subvolume in this directory. So explicitly
  // guard against this case here.
  if !snapshot_only && dst.file_ops.is_dir(subvol)? {
    bail!(
      "Cannot restore subvolume {}: a directory with this name exists",
      subvol.display()
    )
  }

  // Restoration of a subvolume involves a subset of the steps we do
  // when we pull a backup: the deployment.
  let () = deploy(src, dst, snapshot)?;

  if !snapshot_only {
    // Now that we got the snapshot back on the destination repository,
    // we can restore the actual subvolume from it.
    let readonly = true;
    let () = dst
      .btrfs
      .snapshot(&dst.path().join(snapshot.to_string()), subvol, !readonly)?;
  }
  Ok(())
}


/// Purge old snapshots of a subvolume from the provided repository.
pub fn purge(repo: &Repo, subvol: &Path, tag: &str, keep_for: Duration) -> Result<()> {
  let snapshots = repo
    .snapshots()
    .context("failed to list snapshots")?
    .into_iter()
    .map(|(snapshot, _generation)| snapshot)
    .filter(|snapshot| snapshot.subvol == Subvol::new(subvol) && snapshot.tag == tag);

  let current_time = current_time();
  let mut to_purge = snapshots
    .clone()
    .filter(|snapshot| current_time > snapshot.timestamp + keep_for);

  // If we are about to delete all snapshots for the provided
  // subvolume, make sure to keep the most recent one around.
  if to_purge.clone().count() == snapshots.count() {
    let _skipped = to_purge.next_back();
  }

  let () = to_purge.try_for_each(|snapshot| {
    repo.delete(&snapshot).with_context(|| {
      format!(
        "failed to delete snapshot {} in {}",
        snapshot,
        repo.path().display()
      )
    })
  })?;

  Ok(())
}


/// A builder for `Repo` objects.
#[derive(Clone, Debug, Default)]
pub struct RepoBuilder {
  /// The set of file operations to use.
  file_ops: Option<Rc<dyn FileOps>>,
  /// The `Btrfs` instance to use.
  btrfs: Option<Btrfs>,
}

impl RepoBuilder {
  /// Set the `FileOps` instance to use.
  pub fn set_file_ops<O>(&mut self, file_ops: O)
  where
    O: FileOps + 'static,
  {
    self.file_ops = Some(Rc::new(file_ops))
  }

  /// Set the `Btrfs` instance to use.
  pub fn set_btrfs_ops(&mut self, btrfs: Btrfs) {
    self.btrfs = Some(btrfs)
  }

  /// Build the `Repo` object.
  pub fn build<P>(self, directory: P) -> Result<Repo>
  where
    P: AsRef<Path>,
  {
    let file_ops = self.file_ops.unwrap_or_else(|| Rc::new(LocalOps));
    let directory = directory.as_ref();
    let () = file_ops
      .create_dir_all(directory)
      .with_context(|| format!("could not ensure directory {} exists", directory.display()))?;

    let directory = file_ops
      .canonicalize(directory)
      .with_context(|| format!("failed to canonicalize path {}", directory.display()))?;

    let btrfs = self.btrfs.unwrap_or_default();
    let root = find_root(&btrfs, &directory)?;

    let repo = Repo {
      file_ops,
      btrfs,
      // SANITY: Our detected btrfs root directory should always be a
      //         prefix of `directory`.
      repo_root: directory
        .strip_prefix(&root)
        .expect("btrfs root directory is not a prefix of the provided directory")
        .to_path_buf(),
      btrfs_root: root,
    };
    Ok(repo)
  }
}


/// A repository used for managing btrfs snapshots.
#[derive(Clone, Debug)]
pub struct Repo {
  /// The set of file operations to use.
  file_ops: Rc<dyn FileOps>,
  /// Our btrfs API.
  btrfs: Btrfs,
  /// The containing btrfs filesystem's root. This path has been
  /// canonicalized.
  btrfs_root: PathBuf,
  /// The repository's root directory, as a path relative to
  /// `btrfs_root`.
  repo_root: PathBuf,
}

impl Repo {
  /// Create a `RepoBuilder` object.
  pub fn builder() -> RepoBuilder {
    RepoBuilder::default()
  }

  /// Create a new `Repo` object, with `directory` as the root.
  #[cfg(test)]
  pub fn new<P>(directory: P) -> Result<Self>
  where
    P: AsRef<Path>,
  {
    Self::builder().build(directory)
  }

  /// Create a snapshot of the given subvolume in this repository.
  ///
  /// If an up-to-date snapshot is present already, just return it
  /// directly.
  pub fn snapshot(&self, subvol: &Path, tag: &str) -> Result<Snapshot> {
    let snapshots = self.snapshots()?;
    // When searching for the most recent snapshot in this context we
    // are looking for one with not just any but this specific tag.
    let most_recent = find_most_recent_snapshot(&snapshots, subvol, Some(tag))?;

    let parent = if let Some((snapshot, generation)) = most_recent {
      let has_changes = self.btrfs.has_changes(subvol, *generation)?;
      if !has_changes {
        return Ok(snapshot.clone())
      }
      Some(snapshot)
    } else {
      None
    };

    // At this point we know that we have to create a new snapshot for
    // the given subvolume, either because no snapshot was present or
    // because the subvolume has changed since it had been captured.
    let mut snapshot = Snapshot::from_subvol_path(subvol, tag)?;
    debug_assert_eq!(snapshot.number, None);

    // `parent` here is just referring to the most recent snapshot.
    if let Some(most_recent) = parent {
      // If the snapshot has the same base information as the most
      // recent one (including time stamp), disambiguate it by using the
      // most recent snapshot's number incremented by one. The snapshot
      // is then guaranteed to be unique.
      if snapshot == most_recent.strip_number() {
        snapshot = most_recent.bump_number();
      }
    }

    let readonly = true;
    let snapshot_path = self.path().join(snapshot.to_string());
    let () = self.btrfs.snapshot(subvol, &snapshot_path, readonly)?;
    Ok(snapshot)
  }

  /// Delete the provided snapshot from the repository.
  pub fn delete(&self, snapshot: &Snapshot) -> Result<()> {
    let snapshot_path = self.path().join(snapshot.to_string());
    let () = self.btrfs.delete_subvol(&snapshot_path)?;
    Ok(())
  }

  /// Retrieve a list of snapshots in this repository.
  ///
  /// The list is sorted by a per-snapshot-base-name buckets, with the
  /// most recent snapshot being last in each such bucket.
  /// Each snapshot is accompanied by its current btrfs generation
  /// number. All subvolumes present in this repository that do not
  /// match the snapshot format are silently ignored, as they could not
  /// have been generated by the program.
  pub fn snapshots(&self) -> Result<Vec<(Snapshot, usize)>> {
    let readonly = true;
    let mut snapshots = self
      .btrfs
      .subvolumes(
        self.file_ops.deref(),
        &self.btrfs_root,
        Some(&self.repo_root),
        readonly,
      )?
      .into_iter()
      // We are only interested in snapshots *directly* inside of
      // `repo_root`.
      .filter_map(|(path, gen)| {
        // For relative paths, Path::parent returns Some("") if there is
        // no parent.
        if path.parent() == Some(Path::new("")) {
          path
            .file_name()
            .and_then(|snapshot| Snapshot::from_snapshot_name(snapshot).ok())
            .map(|snapshot| (snapshot, gen))
        } else {
          None
        }
      })
      .collect::<Vec<_>>();
    let () = snapshots.sort();

    Ok(snapshots)
  }

  /// Retrieve the path to the repository.
  #[inline]
  pub fn path(&self) -> PathBuf {
    self.btrfs_root.join(&self.repo_root)
  }
}


#[cfg(test)]
mod tests {
  use super::*;

  use std::fs::read_to_string;
  use std::fs::write;

  use serial_test::serial;

  use crate::snapshot::Subvol;
  use crate::test::with_btrfs;
  use crate::test::with_two_btrfs;
  use crate::test::BtrfsDev;
  use crate::test::Mount;


  /// Check that we can create a snapshot of a subvolume.
  #[test]
  #[serial]
  fn snapshot_creation() {
    let tag = "";

    with_btrfs(|root| {
      let btrfs = Btrfs::new();
      let subvol = root.join("subvol");
      let () = btrfs.create_subvol(&subvol).unwrap();
      let () = write(subvol.join("file"), "test42").unwrap();

      let repo = Repo::new(root.join("repo")).unwrap();

      let snapshot = repo.snapshot(&subvol, tag).unwrap();
      let content = read_to_string(repo.path().join(snapshot.to_string()).join("file")).unwrap();
      assert_eq!(content, "test42");
    })
  }

  /// Check that we can create a snapshot with a tag.
  #[test]
  #[serial]
  fn tagged_snapshot_creation() {
    let tag = "tagged";

    with_btrfs(|root| {
      let btrfs = Btrfs::new();
      let subvol = root.join("subvol");
      let () = btrfs.create_subvol(&subvol).unwrap();
      let () = write(subvol.join("file"), "test42").unwrap();

      let repo = Repo::new(root.join("repo")).unwrap();

      let snapshot = repo.snapshot(&subvol, tag).unwrap();
      assert_eq!(snapshot.tag, tag);

      let content = read_to_string(repo.path().join(snapshot.to_string()).join("file")).unwrap();
      assert_eq!(content, "test42");
    })
  }

  /// Make sure that we do not create a new snapshot if a subvolume has
  /// not changed over its most recent snapshot.
  #[test]
  #[serial]
  fn snapshot_creation_up_to_date() {
    let tag = "";

    with_btrfs(|root| {
      let btrfs = Btrfs::new();
      let subvol = root.join("subvol");
      let () = btrfs.create_subvol(&subvol).unwrap();
      let () = write(subvol.join("file"), "test42").unwrap();

      let repo = Repo::new(root).unwrap();

      let snapshot1 = repo.snapshot(&subvol, tag).unwrap();
      let snapshot2 = repo.snapshot(&subvol, tag).unwrap();
      assert_eq!(snapshot1, snapshot2);

      let snapshots = repo.snapshots().unwrap();
      assert_eq!(snapshots.len(), 1);
    })
  }

  /// Make sure that we do create a new snapshot if an untagged
  /// up-to-date snapshot exists, but not a tagged one.
  #[test]
  #[serial]
  fn snapshot_creation_up_to_date_tagged() {
    with_btrfs(|root| {
      let btrfs = Btrfs::new();
      let subvol = root.join("subvol");
      let () = btrfs.create_subvol(&subvol).unwrap();
      let () = write(subvol.join("file"), "test42").unwrap();

      let repo = Repo::new(root).unwrap();

      let tag = "";
      let snapshot1 = repo.snapshot(&subvol, tag).unwrap();
      let tag = "different";
      let snapshot2 = repo.snapshot(&subvol, tag).unwrap();
      assert_ne!(snapshot1, snapshot2);

      let snapshots = repo.snapshots().unwrap();
      assert_eq!(snapshots.len(), 2);
    })
  }

  /// Make sure that we create a new snapshot if a subvolume has changed
  /// over its most recent snapshot.
  #[test]
  #[serial]
  fn snapshot_creation_on_change() {
    let tag = "";

    with_btrfs(|root| {
      let btrfs = Btrfs::new();
      let subvol = root.join("subvol");
      let () = btrfs.create_subvol(&subvol).unwrap();
      let () = write(subvol.join("file"), "test42").unwrap();

      let repo = Repo::new(root).unwrap();

      let snapshot1 = repo.snapshot(&subvol, tag).unwrap();
      let () = write(subvol.join("file"), "test43").unwrap();
      let snapshot2 = repo.snapshot(&subvol, tag).unwrap();
      assert_ne!(snapshot1, snapshot2);

      let snapshots = repo.snapshots().unwrap();
      assert_eq!(snapshots.len(), 2);

      let content = read_to_string(repo.path().join(snapshot1.to_string()).join("file")).unwrap();
      assert_eq!(content, "test42");
      let content = read_to_string(repo.path().join(snapshot2.to_string()).join("file")).unwrap();
      assert_eq!(content, "test43");
    })
  }

  /// Check that no snapshots are reported in an empty repository.
  #[test]
  #[serial]
  fn no_snapshots_in_empty_repo() {
    with_btrfs(|root| {
      let repo = Repo::new(root).unwrap();

      let snapshots = repo.snapshots().unwrap();
      assert!(snapshots.is_empty());
    })
  }

  /// Check that we can create a snapshot of a subvolume and that it is
  /// being returned as part of the snapshot listing.
  #[test]
  #[serial]
  fn snapshot_listing() {
    let tag = "";

    with_btrfs(|root| {
      let btrfs = Btrfs::new();
      let subvol = root.join("subvol");
      let () = btrfs.create_subvol(&subvol).unwrap();

      let repo = Repo::new(root.join("repo")).unwrap();

      let snapshot = repo.snapshot(&subvol, tag).unwrap();
      let mut snapshots = repo.snapshots().unwrap().into_iter();
      assert_eq!(snapshots.len(), 1);

      let next = snapshots.next().unwrap();
      assert_eq!(next.0.subvol, Subvol::new(&subvol));
      assert_eq!(next.0.subvol, snapshot.subvol);
      assert_ne!(next.1, 0);
    })
  }

  /// Make sure that we ignore snapshots outside of a repository.
  #[test]
  #[serial]
  fn snapshot_outside_repo() {
    let tag = "";

    with_btrfs(|root| {
      let btrfs = Btrfs::new();
      let subvol = root.join("subvol");
      let () = btrfs.create_subvol(&subvol).unwrap();

      // Our "business" repository.
      let repo = Repo::new(root.join("repo")).unwrap();

      // One repository in the root.
      let root_repo = Repo::new(root).unwrap();
      let _snapshot = root_repo.snapshot(&subvol, tag).unwrap();

      // And another one below ours.
      let sub_repo = Repo::new(repo.path().join("foobar")).unwrap();
      let _snapshot = sub_repo.snapshot(&subvol, tag).unwrap();

      // None of the other repositories' snapshots should appear in our
      // listing.
      let snapshots = repo.snapshots().unwrap();
      assert!(snapshots.is_empty());
    })
  }

  /// Make sure that only read-only subvolumes are considered as
  /// snapshots.
  #[test]
  #[serial]
  fn writable_snapshot_listing() {
    let tag = "";

    with_btrfs(|root| {
      let btrfs = Btrfs::new();
      let snapshot = Snapshot::from_subvol_path(Path::new("/foobar"), tag).unwrap();
      let subvol = root.join(snapshot.to_string());
      // Create a writable subvolume with a valid snapshot name.
      let () = btrfs.create_subvol(&subvol).unwrap();

      let repo = Repo::new(root).unwrap();
      // Because the subvolume is writable, it should not be produced in
      // the snapshot listing.
      let snapshots = repo.snapshots().unwrap();
      assert!(snapshots.is_empty());
    })
  }

  /// Check that we can backup a subvolume across file system
  /// boundaries.
  #[test]
  #[serial]
  fn backup_subvolume() {
    let tag = "";

    with_two_btrfs(|src_root, dst_root| {
      let src = Repo::new(src_root).unwrap();
      let dst = Repo::new(dst_root).unwrap();

      let btrfs = Btrfs::new();
      let subvol = src_root.join("subvol");
      let () = btrfs.create_subvol(&subvol).unwrap();
      let () = write(subvol.join("file"), "test42").unwrap();

      let snapshot = backup(&src, &dst, &subvol, tag).unwrap();
      let content = read_to_string(dst.path().join(snapshot.to_string()).join("file")).unwrap();
      assert_eq!(content, "test42");
    })
  }

  /// Check that we can backup a subvolume mounted with the `subvol`
  /// option.
  #[test]
  #[serial]
  fn backup_subvolume_with_subvol_option() {
    let src_loopdev = BtrfsDev::with_default().unwrap();

    {
      let src_mount = Mount::new(src_loopdev.path()).unwrap();
      let btrfs = Btrfs::new();
      let subvol = src_mount.path().join("some-subvol");
      let () = btrfs.create_subvol(&subvol).unwrap();
      let () = write(subvol.join("file"), "test42").unwrap();
    }

    let src_mount = Mount::builder()
      .options(["subvol=some-subvol"])
      .mount(src_loopdev.path())
      .unwrap();
    let src_root = src_mount.path();
    assert!(src_root.join("file").exists());

    let dst_loopdev = BtrfsDev::with_default().unwrap();
    let dst_mount = Mount::new(dst_loopdev.path()).unwrap();
    let dst_root = dst_mount.path();

    let src = Repo::new(src_root).unwrap();
    let dst = Repo::new(dst_root).unwrap();

    let subvol = src_mount.path();
    let () = write(subvol.join("file"), "test42").unwrap();

    let tag = "";
    let snapshot = backup(&src, &dst, subvol, tag).unwrap();
    let content = read_to_string(dst.path().join(snapshot.to_string()).join("file")).unwrap();
    assert_eq!(content, "test42");
  }

  /// Check that we error out as expected when attempting to backup a
  /// non-existent subvolume.
  #[test]
  #[serial]
  fn backup_non_existent_subvolume() {
    let tag = "";

    with_two_btrfs(|src_root, dst_root| {
      let src = Repo::new(src_root).unwrap();
      let dst = Repo::new(dst_root).unwrap();

      let subvol = src_root.join("subvol");
      let error = backup(&src, &dst, &subvol, tag).unwrap_err();
      assert!(error.to_string().contains("No such file or directory"));
    })
  }

  /// Make sure that if the subvolume to backup is already up-to-date
  /// with respect to a snapshot, no additional work is done.
  #[test]
  #[serial]
  fn backup_subvolume_up_to_date() {
    let tag = "";

    with_two_btrfs(|src_root, dst_root| {
      let src = Repo::new(src_root).unwrap();
      let dst = Repo::new(dst_root).unwrap();

      let btrfs = Btrfs::new();
      let subvol = src_root.join("subvol");
      let () = btrfs.create_subvol(&subvol).unwrap();

      let snapshot1 = backup(&src, &dst, &subvol, tag).unwrap();
      let snapshot2 = backup(&src, &dst, &subvol, tag).unwrap();
      assert_eq!(snapshot1, snapshot2);

      let snapshots = dst.snapshots().unwrap();
      assert_eq!(snapshots.len(), 1);
    })
  }

  // TODO: Ideally we'd have a test that checks that incremental backups
  //       cause less data to be transferred to make sure that we are
  //       doing everything right, but currently that's not easily
  //       possible to check for.

  /// Make sure that incremental backups can be pulled.
  #[test]
  #[serial]
  fn backup_subvolume_incremental() {
    let tag = "";

    with_two_btrfs(|src_root, dst_root| {
      let src = Repo::new(src_root).unwrap();
      let dst = Repo::new(dst_root).unwrap();

      let btrfs = Btrfs::new();
      let subvol = src_root.join("subvol");
      let () = btrfs.create_subvol(&subvol).unwrap();

      let _snapshot = backup(&src, &dst, &subvol, tag).unwrap();

      for i in 0..20 {
        let string = "test".to_string() + &i.to_string();
        let () = write(subvol.join("file"), &string).unwrap();

        let snapshot = backup(&src, &dst, &subvol, tag).unwrap();
        let content = read_to_string(dst.path().join(snapshot.to_string()).join("file")).unwrap();
        assert_eq!(content, string);
      }
    })
  }

  /// Check that we can restore a subvolume from a snapshot.
  #[test]
  #[serial]
  fn restore_subvolume() {
    let tag = "";

    with_two_btrfs(|src_root, dst_root| {
      let src = Repo::new(src_root).unwrap();
      let dst = Repo::new(dst_root).unwrap();

      let btrfs = Btrfs::new();
      let subvol = src_root.join("subvol");
      let () = btrfs.create_subvol(&subvol).unwrap();
      let () = write(subvol.join("file"), "test42").unwrap();

      // Backup the subvolume to the destination repository.
      let snapshot = backup(&src, &dst, &subvol, tag).unwrap();
      // Then remove the source snapshot and the source subvolume.
      let () = src.delete(&snapshot).unwrap();
      assert!(!src.path().join(snapshot.to_string()).join("file").exists());

      let () = btrfs.delete_subvol(&subvol).unwrap();
      assert!(!subvol.join("file").exists());

      // And lastly, attempt restoration of both.
      let snapshot_only = false;
      let () = restore(&dst, &src, &subvol, snapshot_only).unwrap();

      // The snapshot should be back with the respective content.
      let content = read_to_string(src.path().join(snapshot.to_string()).join("file")).unwrap();
      assert_eq!(content, "test42");

      // And so should the subvolume.
      let content = read_to_string(subvol.join("file")).unwrap();
      assert_eq!(content, "test42");
    })
  }

  /// Check that we can restore only a snapshot.
  #[test]
  #[serial]
  fn restore_snapshot_only() {
    let tag = "";

    with_two_btrfs(|src_root, dst_root| {
      let src = Repo::new(src_root).unwrap();
      let dst = Repo::new(dst_root).unwrap();

      let btrfs = Btrfs::new();
      let subvol = src_root.join("subvol");
      let () = btrfs.create_subvol(&subvol).unwrap();
      let () = write(subvol.join("file"), "test42").unwrap();

      let snapshot = backup(&src, &dst, &subvol, tag).unwrap();
      let () = src.delete(&snapshot).unwrap();

      let snapshot_only = true;
      let () = restore(&dst, &src, &subvol, snapshot_only).unwrap();

      // The snapshot should be back with the respective content.
      let content = read_to_string(src.path().join(snapshot.to_string()).join("file")).unwrap();
      assert_eq!(content, "test42");
    })
  }

  /// Check that we fail subvolume restoration if the subvolume already
  /// exists.
  #[test]
  #[serial]
  fn restore_subvolume_exists() {
    let tag = "";

    with_two_btrfs(|src_root, dst_root| {
      let src = Repo::new(src_root).unwrap();
      let dst = Repo::new(dst_root).unwrap();

      let btrfs = Btrfs::new();
      let subvol = src_root.join("subvol");
      let () = btrfs.create_subvol(&subvol).unwrap();

      let snapshot = backup(&src, &dst, &subvol, tag).unwrap();
      // Then remove the source snapshot and the source subvolume.
      let () = src.delete(&snapshot).unwrap();

      // And lastly, attempt restoration of both.
      let snapshot_only = false;
      let error = restore(&dst, &src, &subvol, snapshot_only).unwrap_err();
      assert!(error
        .to_string()
        .contains("a directory with this name exists"));
    })
  }

  /// Check that we fail subvolume restoration if no suitable snapshot
  /// is present to restore from.
  #[test]
  #[serial]
  fn restore_subvolume_missing_snapshot() {
    let tag = "";

    with_two_btrfs(|src_root, dst_root| {
      let src = Repo::new(src_root).unwrap();
      let dst = Repo::new(dst_root).unwrap();

      let btrfs = Btrfs::new();
      let subvol = src_root.join("subvol");
      let () = btrfs.create_subvol(&subvol).unwrap();

      let snapshot = backup(&src, &dst, &subvol, tag).unwrap();
      // Then remove the just created snapshot.
      let () = dst.delete(&snapshot).unwrap();

      let snapshot_only = false;
      let error = restore(&dst, &src, &subvol, snapshot_only).unwrap_err();
      assert!(error.to_string().contains("No snapshot to restore found"));
    })
  }
}