1"""
2btrfs-snap.py: source target newname
3
4creates a exactly named snapshots and bails out if they exist
5"""
6
7import argparse
8import fcntl
9import os
10import sys
11
12import cffi
13
14ffi = cffi.FFI()
15
16ffi.cdef("""
17    #define BTRFS_IOC_SNAP_CREATE_V2 ...
18    struct btrfs_ioctl_vol_args_v2 {
19        int64_t fd;
20        char name[];
21        ...;
22    };
23""")
24
25ffi.set_source("_btrfs_cffi", "#include <btrfs/ioctl.h>")
26ffi.compile()
27
28# ____________________________________________________________
29
30
31from _btrfs_cffi import ffi, lib
32
33parser = argparse.ArgumentParser(usage=__doc__.strip())
34parser.add_argument('source', help='source subvolume')
35parser.add_argument('target', help='target directory')
36parser.add_argument('newname', help='name of the new snapshot')
37opts = parser.parse_args()
38
39source = os.open(opts.source, os.O_DIRECTORY)
40target = os.open(opts.target, os.O_DIRECTORY)
41
42
43args = ffi.new('struct btrfs_ioctl_vol_args_v2 *')
44args.name = opts.newname
45args.fd = source
46args_buffer = ffi.buffer(args)
47try:
48    fcntl.ioctl(target, lib.BTRFS_IOC_SNAP_CREATE_V2, args_buffer)
49except IOError as e:
50    print e
51    sys.exit(1)
52
53