libzetta 0.5.0

libzetta is a stable interface for programmatic administration of ZFS
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
use crate::{
    zfs::{
        BookmarkRequest, Checksum, Compression, Copies, CreateDatasetRequest, DatasetKind,
        DestroyTiming, Error, Result, SendFlags, SnapDir, ValidationError, ZfsEngine,
    },
    GlobalLogger,
};
use cstr_argument::CStrArgument;
use libnv::nvpair::NvList;
use slog::Logger;

use crate::zfs::{
    errors::Error::ValidationErrors,
    properties::{AclInheritMode, AclMode, ZfsProp},
    PathExt,
};
use std::{
    collections::HashMap,
    ffi::CString,
    os::unix::io::{AsRawFd, RawFd},
    path::PathBuf,
    ptr::null_mut,
};
use zfs_core_sys as sys;

#[cfg(target_os = "freebsd")]
const ECHRNG: libc::c_int = libc::ENXIO;
#[cfg(target_os = "linux")]
const ECHRNG: libc::c_int = libc::ECHRNG;

#[derive(Debug, Clone)]
pub struct ZfsLzc {
    logger: Logger,
}

impl ZfsLzc {
    /// Initialize libzfs_core backed ZfsEngine.
    /// If root logger is None, then StdLog drain used.
    pub fn new() -> Result<Self> {
        let errno = unsafe { sys::libzfs_core_init() };

        if errno != 0 {
            let io_error = std::io::Error::from_raw_os_error(errno);
            return Err(Error::LZCInitializationFailed(io_error));
        }
        let logger = GlobalLogger::get().new(o!("zetta_module" => "zfs", "zfs_impl" => "lzc"));

        Ok(ZfsLzc { logger })
    }

    pub fn logger(&self) -> &Logger {
        &self.logger
    }

    fn send(
        &self,
        path: PathBuf,
        from: Option<PathBuf>,
        fd: RawFd,
        flags: SendFlags,
    ) -> Result<()> {
        let snapshot =
            CString::new(path.to_str().unwrap()).expect("Failed to create CString from path");
        let snapshot_ptr = snapshot.as_ptr();
        let from_cstr = from.map(|f| {
            CString::new(f.to_str().unwrap()).expect("Failed to create CString from path")
        });
        let fd_raw = fd;
        let errno = if let Some(src) = from_cstr {
            unsafe { zfs_core_sys::lzc_send(snapshot_ptr, src.as_ptr(), fd_raw, flags.bits) }
        } else {
            unsafe { zfs_core_sys::lzc_send(snapshot_ptr, std::ptr::null(), fd_raw, flags.bits) }
        };

        match errno {
            0 => Ok(()),
            _ => {
                let io_error = std::io::Error::from_raw_os_error(errno);
                Err(Error::Io(io_error))
            }
        }
    }
}

impl ZfsEngine for ZfsLzc {
    fn exists<N: Into<PathBuf>>(&self, name: N) -> Result<bool> {
        let path = name.into();
        let n = path.to_str().expect("Invalid Path").into_cstr();
        let ret = unsafe { sys::lzc_exists(n.as_ref().as_ptr()) };

        if ret == 1 {
            Ok(true)
        } else {
            Ok(false)
        }
    }

    fn create(&self, request: CreateDatasetRequest) -> Result<()> {
        request.validate()?;

        //let mut props = nvpair::NvList::new()?;
        let mut props = NvList::default();
        let name_c_string =
            CString::new(request.name().to_str().expect("Non UTF-8 name")).expect("NULL in name");
        // LZC wants _everything_ as u64 even booleans.
        if let Some(acl_inherit) = request.acl_inherit {
            props.insert_u64(AclInheritMode::nv_key(), acl_inherit.as_nv_value())?;
        }
        if let Some(acl_mode) = request.acl_mode {
            props.insert_u64(AclMode::nv_key(), acl_mode.as_nv_value())?;
        }
        if let Some(atime) = request.atime {
            props.insert_u64("atime", bool_to_u64(atime))?;
        }
        if let Some(checksum) = request.checksum {
            props.insert_u64(Checksum::nv_key(), checksum.as_nv_value())?;
        }
        if let Some(compression) = request.compression {
            props.insert_u64(Compression::nv_key(), compression.as_nv_value())?;
        }
        if let Some(copies) = request.copies() {
            props.insert_u64(Copies::nv_key(), copies.as_nv_value())?;
        }
        if let Some(devices) = request.devices {
            props.insert_u64("devices", bool_to_u64(devices))?;
        }
        if let Some(exec) = request.exec {
            props.insert_u64("exec", bool_to_u64(exec))?;
        }
        // saved fore mount point
        if let Some(primary_cache) = request.primary_cache {
            props.insert_u64("primarycache", primary_cache.as_nv_value())?;
        }
        if let Some(quota) = request.quota {
            props.insert_u64("quota", quota)?;
        }
        if let Some(readonly) = request.readonly {
            props.insert_u64("readonly", bool_to_u64(readonly))?;
        }
        if let Some(record_size) = request.record_size {
            props.insert_u64("recordsize", record_size)?;
        }
        if let Some(ref_quota) = request.ref_quota {
            props.insert_u64("refquota", ref_quota)?;
        }
        if let Some(ref_reservation) = request.ref_reservation {
            props.insert_u64("refreservation", ref_reservation)?;
        }
        if let Some(secondary_cache) = request.secondary_cache {
            props.insert_u64("secondarycache", secondary_cache.as_nv_value())?;
        }
        if let Some(setuid) = request.setuid {
            props.insert_u64("setuid", bool_to_u64(setuid))?;
        }
        if let Some(snap_dir) = request.snap_dir {
            props.insert_u64(SnapDir::nv_key(), snap_dir.as_nv_value())?;
        }

        if request.kind == DatasetKind::Filesystem
            && (request.volume_size.is_some() || request.volume_block_size.is_some())
        {
            return Err(Error::invalid_input());
        }

        if request.kind == DatasetKind::Volume && request.volume_size.is_none() {
            return Err(Error::invalid_input());
        }

        if let Some(vol_size) = request.volume_size {
            props.insert_u64("volsize", vol_size)?;
        }
        if let Some(vol_block_size) = request.volume_block_size {
            props.insert_u64("volblocksize", vol_block_size)?;
        }

        if let Some(xattr) = request.xattr {
            props.insert("xattr", bool_to_u64(xattr))?;
        }
        if let Some(user_props) = request.user_properties() {
            for (key, value) in user_props {
                props.insert_string(key.as_str(), value.as_str())?;
            }
        }
        let errno = unsafe {
            zfs_core_sys::lzc_create(
                name_c_string.as_ref().as_ptr(),
                request.kind().as_c_uint(),
                props.as_ptr(),
                std::ptr::null_mut(),
                0,
            )
        };

        match errno {
            0 => Ok(()),
            _ => {
                let io_error = std::io::Error::from_raw_os_error(errno);
                Err(Error::Io(io_error))
            }
        }
    }

    fn snapshot(
        &self,
        snapshots: &[PathBuf],
        user_properties: Option<HashMap<String, String>>,
    ) -> Result<()> {
        let validation_errors: Vec<ValidationError> = snapshots
            .iter()
            .map(PathBuf::validate)
            .filter_map(Result::err)
            .collect();
        if !validation_errors.is_empty() {
            return Err(ValidationErrors(validation_errors));
        }

        let mut snapshots_list = NvList::default();
        let mut props = NvList::default();
        for snap in snapshots {
            snapshots_list.insert(&*snap.to_string_lossy(), true)?;
        }
        let mut errors_list_ptr = null_mut();
        if let Some(user_properties) = user_properties {
            for (key, value) in user_properties {
                props.insert_string(key.as_str(), value.as_str())?;
            }
        }
        let errno = unsafe {
            zfs_core_sys::lzc_snapshot(
                snapshots_list.as_ptr(),
                props.as_ptr(),
                &mut errors_list_ptr,
            )
        };
        if !errors_list_ptr.is_null() {
            let errors = unsafe { NvList::from_ptr(errors_list_ptr) };
            if !errors.is_empty() {
                return Err(Error::from(errors.into_hashmap()));
            }
        }
        match errno {
            0 => Ok(()),
            _ => {
                let io_error = std::io::Error::from_raw_os_error(errno);
                Err(Error::Io(io_error))
            }
        }
    }

    fn bookmark(&self, bookmarks: &[BookmarkRequest]) -> Result<()> {
        let validation_errors: Vec<ValidationError> = bookmarks
            .iter()
            .flat_map(|BookmarkRequest { snapshot, bookmark }| vec![snapshot, bookmark])
            .map(PathBuf::validate)
            .filter_map(Result::err)
            .collect();
        if !validation_errors.is_empty() {
            return Err(ValidationErrors(validation_errors));
        }

        let mut bookmarks_list = NvList::default();
        for BookmarkRequest { snapshot, bookmark } in bookmarks {
            bookmarks_list.insert(
                &*bookmark.to_string_lossy(),
                snapshot.to_string_lossy().as_ref(),
            )?;
        }

        let mut errors_list_ptr = null_mut();
        let errno =
            unsafe { zfs_core_sys::lzc_bookmark(bookmarks_list.as_ptr(), &mut errors_list_ptr) };
        if !errors_list_ptr.is_null() {
            let errors = unsafe { NvList::from_ptr(errors_list_ptr) };
            if !errors.is_empty() {
                return Err(Error::from(errors.into_hashmap()));
            }
        }
        match errno {
            0 => Ok(()),
            _ => {
                let io_error = std::io::Error::from_raw_os_error(errno);
                Err(Error::Io(io_error))
            }
        }
    }

    fn destroy_snapshots(&self, snapshots: &[PathBuf], timing: DestroyTiming) -> Result<()> {
        let validation_errors: Vec<ValidationError> = snapshots
            .iter()
            .map(PathBuf::validate)
            .filter(Result::is_err)
            .map(Result::unwrap_err)
            .collect();
        if !validation_errors.is_empty() {
            return Err(ValidationErrors(validation_errors));
        }

        let mut snapshots_list = NvList::default();

        for snap in snapshots {
            snapshots_list.insert(&*snap.to_string_lossy(), true)?;
        }

        let mut errors_list_ptr = null_mut();
        let errno = unsafe {
            zfs_core_sys::lzc_destroy_snaps(
                snapshots_list.as_ptr(),
                timing.as_c_uint(),
                &mut errors_list_ptr,
            )
        };
        if !errors_list_ptr.is_null() {
            let errors = unsafe { NvList::from_ptr(errors_list_ptr) };
            if !errors.is_empty() {
                return Err(Error::from(errors.into_hashmap()));
            }
        }
        match errno {
            0 => Ok(()),
            _ => {
                let io_error = std::io::Error::from_raw_os_error(errno);
                Err(Error::Io(io_error))
            }
        }
    }

    fn destroy_bookmarks(&self, bookmarks: &[PathBuf]) -> Result<()> {
        let validation_errors: Vec<ValidationError> = bookmarks
            .iter()
            .map(PathBuf::validate)
            .filter(Result::is_err)
            .map(Result::unwrap_err)
            .collect();
        if !validation_errors.is_empty() {
            return Err(ValidationErrors(validation_errors));
        }

        let mut bookmarks_list = NvList::default();

        for bookmark in bookmarks {
            bookmarks_list.insert_boolean(&*bookmark.to_string_lossy())?;
        }

        let mut errors_list_ptr = null_mut();
        let errno = unsafe {
            zfs_core_sys::lzc_destroy_bookmarks(bookmarks_list.as_ptr(), &mut errors_list_ptr)
        };
        if !errors_list_ptr.is_null() {
            let errors = unsafe { NvList::from_ptr(errors_list_ptr) };
            if !errors.is_empty() {
                return Err(Error::from(errors.into_hashmap()));
            }
        }
        match errno {
            0 => Ok(()),
            _ => {
                let io_error = std::io::Error::from_raw_os_error(errno);
                Err(Error::Io(io_error))
            }
        }
    }

    fn send_full<N: Into<PathBuf>, FD: AsRawFd>(
        &self,
        path: N,
        fd: FD,
        flags: SendFlags,
    ) -> Result<()> {
        self.send(path.into(), None, fd.as_raw_fd(), flags)
    }

    fn send_incremental<N: Into<PathBuf>, F: Into<PathBuf>, FD: AsRawFd>(
        &self,
        path: N,
        from: F,
        fd: FD,
        flags: SendFlags,
    ) -> Result<()> {
        self.send(path.into(), Some(from.into()), fd.as_raw_fd(), flags)
    }

    fn run_channel_program<N: Into<PathBuf>>(
        &self,
        pool: N,
        program: &str,
        instr_limit: u64,
        mem_limit: u64,
        sync: bool,
        args: NvList,
    ) -> Result<NvList> {
        let pool = pool.into();
        let pool_c_string = pool.to_str().expect("Non UTF-8 pool name").into_cstr();
        let prog_c_string = program.into_cstr();

        let mut out_nvlist_ptr = null_mut();
        let errno = unsafe {
            if sync {
                zfs_core_sys::lzc_channel_program(
                    pool_c_string.as_ref().as_ptr(),
                    prog_c_string.as_ref().as_ptr(),
                    instr_limit,
                    mem_limit,
                    args.as_ptr(),
                    &mut out_nvlist_ptr,
                )
            } else {
                zfs_core_sys::lzc_channel_program_nosync(
                    pool_c_string.as_ref().as_ptr(),
                    prog_c_string.as_ref().as_ptr(),
                    instr_limit,
                    mem_limit,
                    args.as_ptr(),
                    &mut out_nvlist_ptr,
                )
            }
        };
        match errno {
            0 => Ok(unsafe { NvList::from_ptr(out_nvlist_ptr) }),
            libc::EINVAL => Err(Error::ChanProgInval(
                unsafe { NvList::from_ptr(out_nvlist_ptr) }.into_hashmap(),
            )),
            ECHRNG => Err(Error::ChanProgRuntime(
                unsafe { NvList::from_ptr(out_nvlist_ptr) }.into_hashmap(),
            )),
            _ => {
                let io_error = std::io::Error::from_raw_os_error(errno);
                Err(Error::Io(io_error))
            }
        }
    }
}

// This should be mapped to values from nvpair.
fn bool_to_u64(src: bool) -> u64 {
    if src {
        1
    } else {
        0
    }
}