1#
2# Copyright (C) Stanislaw Adaszewski, 2020
3# License: GNU General Public License v3.0
4# URL: https://github.com/sadaszewski/focker
5# URL: https://adared.ch/focker
6#
7
8from .zfs import *
9from .misc import focker_lock, \
10    focker_unlock
11
12
13def new_snapshot(base, fun, name, props={}):
14    type_ = zfs_get_type(base)
15    if type_ != 'snapshot':
16        raise ValueError('Provided base dataset is not a snapshot')
17    if '/' not in name:
18        root = '/'.join(base.split('/')[:-1])
19        name = root + '/' + name
20    cmd = [ 'zfs', 'clone' ]
21    for k, v in props.items():
22        cmd.append('-o')
23        cmd.append(k + '=' + v)
24    cmd += [ base, name ]
25    zfs_run(cmd)
26    try:
27        try:
28            focker_unlock()
29            fun()
30        finally:
31            focker_lock()
32        zfs_run(['zfs', 'set', 'readonly=on', name])
33        snap_name = name + '@1'
34        zfs_run(['zfs', 'snapshot', snap_name])
35    except:
36        zfs_run(['zfs', 'destroy', '-f', name])
37        raise
38    return snap_name
39