btrfsutil 0.2.0

Safe wrappers for libbtrfsutil.
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
use crate::common;
use crate::error::LibError;
use crate::qgroup::QgroupInherit;
use crate::subvolume::SubvolumeInfo;
use crate::Result;

use std::convert::TryFrom;
use std::ffi::CString;
use std::path::{Path, PathBuf};

use btrfsutil_sys::btrfs_util_create_snapshot;
use btrfsutil_sys::btrfs_util_create_subvolume;
use btrfsutil_sys::btrfs_util_delete_subvolume;
use btrfsutil_sys::btrfs_util_deleted_subvolumes;
use btrfsutil_sys::btrfs_util_get_default_subvolume;
use btrfsutil_sys::btrfs_util_get_subvolume_read_only;
use btrfsutil_sys::btrfs_util_is_subvolume;
use btrfsutil_sys::btrfs_util_set_default_subvolume;
use btrfsutil_sys::btrfs_util_set_subvolume_read_only;
use btrfsutil_sys::btrfs_util_subvolume_id;
use btrfsutil_sys::btrfs_util_subvolume_path;
use btrfsutil_sys::btrfs_util_wait_sync;

use libc::{c_void, free};

bitflags! {
    /// [Subvolume] delete flags.
    ///
    /// [Subvolume]:struct.Subvolume.html
    pub struct DeleteFlags: i32 {
        /// Recursive.
        const RECURSIVE = btrfsutil_sys::BTRFS_UTIL_DELETE_SUBVOLUME_RECURSIVE as i32;
    }
}
bitflags! {
    /// [Subvolume] snapshot flags.
    ///
    /// [Subvolume]:struct.Subvolume.html
    pub struct SnapshotFlags: i32 {
        /// Read-only.
        const READ_ONLY	= btrfsutil_sys::BTRFS_UTIL_CREATE_SNAPSHOT_READ_ONLY as i32;
        /// Recursive.
        const RECURSIVE = btrfsutil_sys::BTRFS_UTIL_CREATE_SNAPSHOT_RECURSIVE as i32;
    }
}

/// A Btrfs subvolume.
#[derive(Clone, Debug, PartialEq)]
pub struct Subvolume {
    id: u64,
    path: PathBuf,
}

impl Subvolume {
    /// Get a subvolume.
    ///
    /// The path must point to the root of a subvolume.
    pub fn get<'a, P>(path: P) -> Result<Self>
    where
        P: Into<&'a Path>,
    {
        Self::get_impl(path.into())
    }

    fn get_impl(path: &Path) -> Result<Self> {
        Self::is_subvolume(path)?;

        let path_cstr = common::path_to_cstr(path);
        let id: u64 = {
            let mut id: u64 = 0;
            unsafe_wrapper!({ btrfs_util_subvolume_id(path_cstr.as_ptr(), &mut id) })?;
            id
        };

        Ok(Subvolume::new(id, path.into()))
    }

    /// Get a subvolume anyway.
    ///
    /// If the path is not the root of a subvolume, attempts to use btrfs_util_subvolume_path to
    /// get it, which requires **CAP_SYS_ADMIN**.
    ///
    /// ![Requires **CAP_SYS_ADMIN**](https://img.shields.io/static/v1?label=Requires&message=CAP_SYS_ADMIN&color=informational)
    pub fn get_anyway<'a, P>(path: P) -> Result<Self>
    where
        P: Into<&'a Path>,
    {
        Self::get_anyway_impl(path.into())
    }

    fn get_anyway_impl(path: &Path) -> Result<Self> {
        if let Ok(subvol) = Self::get_impl(path) {
            return Ok(subvol);
        }

        let path_cstr = common::path_to_cstr(path);
        let id: u64 = {
            let mut id: u64 = 0;
            unsafe_wrapper!({ btrfs_util_subvolume_id(path_cstr.as_ptr(), &mut id) })?;
            id
        };

        let mut path_ret_ptr: *mut std::os::raw::c_char = std::ptr::null_mut();

        unsafe_wrapper!({ btrfs_util_subvolume_path(path_cstr.as_ptr(), id, &mut path_ret_ptr) })?;

        let path_ret: CString = unsafe { CString::from_raw(path_ret_ptr) };

        Ok(Self::new(id, common::cstr_to_path(&path_ret)))
    }

    /// Create a new subvolume.
    pub fn create<'a, P, Q>(path: P, qgroup: Q) -> Result<Self>
    where
        P: Into<&'a Path>,
        Q: Into<Option<QgroupInherit>>,
    {
        Self::create_impl(path.into(), qgroup.into())
    }

    fn create_impl(path: &Path, qgroup: Option<QgroupInherit>) -> Result<Self> {
        let path_cstr = common::path_to_cstr(path);
        let qgroup_ptr = qgroup.map(|v| v.as_ptr()).unwrap_or(std::ptr::null_mut());

        let transid: u64 = {
            let mut transid: u64 = 0;
            unsafe_wrapper!({
                btrfs_util_create_subvolume(path_cstr.as_ptr(), 0, &mut transid, qgroup_ptr)
            })?;
            transid
        };

        unsafe_wrapper!({ btrfs_util_wait_sync(path_cstr.as_ptr(), transid) })?;

        Self::get(path)
    }

    /// Delete a subvolume.
    pub fn delete<D>(self, flags: D) -> Result<()>
    where
        D: Into<Option<DeleteFlags>>,
    {
        Self::delete_impl(self, flags.into())
    }

    fn delete_impl(self, flags: Option<DeleteFlags>) -> Result<()> {
        let path_cstr = common::path_to_cstr(&self.path);
        let flags_val = flags.map(|v| v.bits()).unwrap_or(0);

        unsafe_wrapper!({ btrfs_util_delete_subvolume(path_cstr.as_ptr(), flags_val) })?;

        Ok(())
    }

    /// Get a list of subvolumes which have been deleted but not yet cleaned up.
    ///
    /// ![Requires **CAP_SYS_ADMIN**](https://img.shields.io/static/v1?label=Requires&message=CAP_SYS_ADMIN&color=informational)
    pub fn deleted<'a, F>(fs_root: F) -> Result<Vec<Self>>
    where
        F: Into<&'a Path>,
    {
        Self::deleted_impl(fs_root.into())
    }

    fn deleted_impl(fs_root: &Path) -> Result<Vec<Subvolume>> {
        // fixme 16/09/2020: you should probably just return the ids
        // since the subvolumes have been deleted, they should probably not have a path.

        let path_cstr = common::path_to_cstr(fs_root);
        let mut ids_ptr: *mut u64 = std::ptr::null_mut();
        let mut ids_count: usize = 0;

        unsafe_wrapper!({
            btrfs_util_deleted_subvolumes(path_cstr.as_ptr(), &mut ids_ptr, &mut ids_count)
        })?;

        if ids_count == 0 {
            return Ok(Vec::new());
        }

        let subvolume_ids: Vec<u64> = unsafe {
            let slice = std::slice::from_raw_parts(ids_ptr, ids_count);
            let vec = slice.to_vec();
            free(ids_ptr as *mut c_void);
            vec
        };

        let subvolumes: Vec<Subvolume> = {
            let mut subvolumes: Vec<Subvolume> = Vec::with_capacity(ids_count);
            for id in subvolume_ids {
                subvolumes.push(Subvolume::try_from(id)?);
            }
            subvolumes
        };

        Ok(subvolumes)
    }

    /// Get the default subvolume.
    ///
    /// ![Requires **CAP_SYS_ADMIN**](https://img.shields.io/static/v1?label=Requires&message=CAP_SYS_ADMIN&color=informational)
    pub fn get_default<'a, P>(path: P) -> Result<Self>
    where
        P: Into<&'a Path>,
    {
        Self::get_default_impl(path.into())
    }

    fn get_default_impl(path: &Path) -> Result<Self> {
        let path_cstr = common::path_to_cstr(path);
        let mut id: u64 = 0;

        unsafe_wrapper!({ btrfs_util_get_default_subvolume(path_cstr.as_ptr(), &mut id) })?;

        Ok(Subvolume::new(id, path.into()))
    }

    /// Set this subvolume as the default subvolume.
    ///
    /// ![Requires **CAP_SYS_ADMIN**](https://img.shields.io/static/v1?label=Requires&message=CAP_SYS_ADMIN&color=informational)
    pub fn set_default(&self) -> Result<()> {
        let path_cstr = common::path_to_cstr(&self.path);

        unsafe_wrapper!({ btrfs_util_set_default_subvolume(path_cstr.as_ptr(), self.id) })?;

        Ok(())
    }

    /// Check whether this subvolume is read-only.
    pub fn is_ro(&self) -> Result<bool> {
        let path_cstr = common::path_to_cstr(&self.path);
        let ro: bool = {
            let mut ro = false;
            unsafe_wrapper!({ btrfs_util_get_subvolume_read_only(path_cstr.as_ptr(), &mut ro) })?;
            ro
        };

        Ok(ro)
    }

    /// Set whether this subvolume is read-only or not.
    ///
    /// ![Requires **CAP_SYS_ADMIN**](https://img.shields.io/static/v1?label=Requires&message=CAP_SYS_ADMIN&color=informational)
    pub fn set_ro(&self, ro: bool) -> Result<()> {
        let path_cstr = common::path_to_cstr(&self.path);

        unsafe_wrapper!({ btrfs_util_set_subvolume_read_only(path_cstr.as_ptr(), ro) })?;

        Ok(())
    }

    /// Check if a path is a Btrfs subvolume.
    ///
    /// Returns Ok if it is a subvolume or Err if otherwise.
    pub fn is_subvolume<'a, P>(path: P) -> Result<()>
    where
        P: Into<&'a Path>,
    {
        Self::is_subvolume_impl(path.into())
    }

    fn is_subvolume_impl(path: &Path) -> Result<()> {
        let path_cstr = common::path_to_cstr(path);

        unsafe_wrapper!({ btrfs_util_is_subvolume(path_cstr.as_ptr()) })
    }

    /// Get information about this subvolume.
    pub fn info(&self) -> Result<SubvolumeInfo> {
        SubvolumeInfo::try_from(self)
    }

    /// Create a snapshot of this subvolume.
    pub fn snapshot<'a, P, F, Q>(&self, path: P, flags: F, qgroup: Q) -> Result<Self>
    where
        P: Into<&'a Path>,
        F: Into<Option<SnapshotFlags>>,
        Q: Into<Option<QgroupInherit>>,
    {
        self.snapshot_impl(path.into(), flags.into(), qgroup.into())
    }

    fn snapshot_impl(
        &self,
        path: &Path,
        flags: Option<SnapshotFlags>,
        qgroup: Option<QgroupInherit>,
    ) -> Result<Self> {
        let path_src_cstr = common::path_to_cstr(&self.path);
        let path_dest_cstr = common::path_to_cstr(path);
        let flags_val = flags.map(|v| v.bits()).unwrap_or(0);
        let qgroup_ptr = qgroup.map(|v| v.as_ptr()).unwrap_or(std::ptr::null_mut());

        let transid: u64 = {
            let mut transid: u64 = 0;
            unsafe_wrapper!({
                btrfs_util_create_snapshot(
                    path_src_cstr.as_ptr(),
                    path_dest_cstr.as_ptr(),
                    flags_val,
                    &mut transid,
                    qgroup_ptr,
                )
            })?;
            transid
        };

        unsafe_wrapper!({ btrfs_util_wait_sync(path_dest_cstr.as_ptr(), transid) })?;

        Self::get(path)
    }

    /// Get the id of this subvolume.
    #[inline]
    pub fn id(&self) -> u64 {
        self.id
    }

    /// Get the path of this subvolume.
    #[inline]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Create a new subvolume from an id and a path.
    ///
    /// Restricted to the crate.
    #[inline]
    pub(crate) fn new(id: u64, path: PathBuf) -> Self {
        Self { id, path }
    }
}

impl From<&Subvolume> for u64 {
    /// Returns the id of the subvolume.
    #[inline]
    fn from(subvolume: &Subvolume) -> u64 {
        subvolume.id
    }
}

impl TryFrom<u64> for Subvolume {
    type Error = LibError;

    /// Attempts to get a subvolume from an id.
    ///
    /// This function will panic if it cannot retrieve the current working directory.
    ///
    /// ![Requires **CAP_SYS_ADMIN**](https://img.shields.io/static/v1?label=Requires&message=CAP_SYS_ADMIN&color=informational)
    fn try_from(src: u64) -> Result<Subvolume> {
        let path_cstr: CString = common::path_to_cstr(
            std::env::current_dir()
                .expect("Could not get the current working directory")
                .as_ref(),
        );
        let mut path_ret_ptr: *mut std::os::raw::c_char = std::ptr::null_mut();

        unsafe_wrapper!({ btrfs_util_subvolume_path(path_cstr.as_ptr(), src, &mut path_ret_ptr) })?;

        let path_ret: CString = unsafe { CString::from_raw(path_ret_ptr) };

        Ok(Self::new(src, common::cstr_to_path(&path_ret)))
    }
}

impl From<&Subvolume> for PathBuf {
    /// Returns the path of the subvolume.
    #[inline]
    fn from(subvolume: &Subvolume) -> Self {
        subvolume.path.clone()
    }
}

impl<'lifetime> From<&'lifetime Subvolume> for &'lifetime Path {
    /// Returns the path of the subvolume.
    #[inline]
    fn from(subvolume: &'lifetime Subvolume) -> Self {
        subvolume.path.as_ref()
    }
}

impl TryFrom<&Path> for Subvolume {
    type Error = LibError;

    /// Attempts to get a subvolume from a path.
    #[inline]
    fn try_from(src: &Path) -> Result<Subvolume> {
        Subvolume::get_impl(src)
    }
}

impl TryFrom<PathBuf> for Subvolume {
    type Error = LibError;

    /// Attempts to get a subvolume from a path.
    #[inline]
    fn try_from(src: PathBuf) -> Result<Subvolume> {
        Subvolume::get_impl(src.as_ref())
    }
}

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

    use std::fs::{create_dir_all, OpenOptions};
    use std::path::Path;

    use nix::mount::{mount, MsFlags};

    use crate::testing::{btrfs_create_fs, test_with_spec};
    use btrfsutil_sys::BTRFS_FS_TREE_OBJECTID;

    fn test_btrfs_subvol(paths: &[&Path]) {
        // Create btrfs filesystem on loopback device
        btrfs_create_fs(paths[0]).unwrap();

        // Create mount point and mount
        let mount_pt = Path::new("/tmp/btrfsutil/mnt");
        create_dir_all(mount_pt).unwrap();
        mount(
            Some(paths[0]),
            mount_pt,
            Some("btrfs"),
            MsFlags::empty(),
            None as Option<&str>,
        )
        .unwrap();

        let root_subvol = Subvolume::try_from(mount_pt).unwrap();
        assert_eq!(root_subvol.id(), BTRFS_FS_TREE_OBJECTID);

        let mut new_sv_path = mount_pt.to_owned();
        new_sv_path.push("subvol1");
        let sv1 = Subvolume::create(&*new_sv_path, None).unwrap();

        // Test path()
        let sv1_abs_path = sv1.path().to_owned();
        assert_eq!(&sv1_abs_path, &new_sv_path, "paths are not equal");

        // Test get_default
        let default_sv = Subvolume::get_default(mount_pt).unwrap();
        assert_eq!(
            default_sv, root_subvol,
            "default subvolume is not the root subvolume"
        );

        // Test set_default
        sv1.set_default().unwrap();
        let new_default_sv = Subvolume::get_default(mount_pt).unwrap();
        assert_eq!(sv1, new_default_sv, "new default subvolume not set");
        assert_eq!(
            new_default_sv.path().canonicalize().unwrap(),
            new_sv_path,
            "default subvolume path does not match"
        );

        // Restore root as default
        root_subvol.set_default().unwrap();

        let info = root_subvol.info().unwrap();
        assert_eq!(info.id, BTRFS_FS_TREE_OBJECTID);
        assert_eq!(info.parent_id, None);
        assert_eq!(info.dir_id, None);
        assert_eq!(info.parent_uuid, None);
        assert_eq!(info.received_uuid, None);

        // Test cannot write to readonly subvolume
        assert_eq!(false, sv1.is_ro().unwrap());
        sv1.set_ro(true).unwrap();
        let mut file_path = sv1_abs_path.clone();
        file_path.push("file.txt");
        assert!(OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&file_path)
            .is_err());

        // Can now create a file
        sv1.set_ro(false).unwrap();
        assert!(OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&file_path)
            .is_ok());

        // Test is_subvolume
        Subvolume::is_subvolume(mount_pt).expect("Valid subvolume failed is_subvolume test");
        Subvolume::is_subvolume(&*new_sv_path).expect("Valid subvolume failed is_subvolume test");
        // Existing non-btrfs path
        Subvolume::is_subvolume(Path::new("/tmp"))
            .expect_err("Existing, non-btrfs path incorrectly flagged as subvolume");
        // Nonexistent path
        Subvolume::is_subvolume(Path::new("/foobar"))
            .expect_err("Nonexistent path incorrectly flagged as subvolume");

        let mut dir_path = sv1_abs_path.clone();
        dir_path.push("dir1");
        create_dir_all(&dir_path).unwrap();
        // A directory within a subvolume is not a subvolume
        Subvolume::is_subvolume(&*dir_path)
            .expect_err("Directory within a subvolume incorrectly flagged as subvolume");

        // Test making a snapshot
        let mut snap_path = mount_pt.to_owned();
        snap_path.push("snap1");
        let snap_sv1 = sv1.snapshot(&*snap_path, None, None).unwrap();
        let mut snap_file_path = snap_path;
        snap_file_path.push("file.txt");

        // File from orig also in snap
        assert!(OpenOptions::new().read(true).open(&snap_file_path).is_ok());

        // Test subvol deletion
        let snap_id = snap_sv1.info().unwrap().id;
        snap_sv1.delete(None).unwrap();

        let deleted = Subvolume::deleted(mount_pt).unwrap();
        assert_eq!(1, deleted.len());
        assert_eq!(snap_id, deleted[0].id());
    }

    #[test]
    #[ignore] // FIXME: refactor and run once build pipeline set up
    fn loop_test_btrfs_subvol() {
        test_with_spec(1, test_btrfs_subvol);
    }
}