Debian Codegraph @

dev/sparse-size

raw
1 #!/bin/sh
2 """": # -*-python-*-
3 bup_python="$(dirname "$0")/bup-python" || exit $?
4 exec "$bup_python" "$0" ${1+"$@"}
5 """
6
7 from argparse import ArgumentParser
8 from os.path import abspath, dirname, getsize
9 from sys import argv, stderr
10
11 def log(*args, **kwargs):
12 if 'file' not in kwargs:
13 kwargs['file'] = stderr
14 if 'end' not in kwargs:
15 kwargs['end'] = ''
16 print(*args, **kwargs)
17
18 try:
19 from os import SEEK_DATA, SEEK_HOLE
20 have_seek_data_hole = True
21 log('sparse-size: relying on SEEK_DATA SEEK_HOLE\n')
22 except ImportError:
23 log('sparse-size: no SEEK_DATA SEEK_HOLE, using du\n')
24 have_seek_data_hole = False
25 if have_seek_data_hole:
26 from errno import ENXIO
27 from os import SEEK_CUR, SEEK_DATA, SEEK_HOLE, lseek
28 else:
29 from os import environb
30 from subprocess import PIPE, run
31 from time import sleep
32
33
34 parser = ArgumentParser()
35 parser.add_argument('-v', dest='verbose', action='count', default=0,
36 help='increase diagnostics (may be repeated)')
37 parser.add_argument('path', metavar='<path>')
38 opt = parser.parse_args()
39
40 if not have_seek_data_hole:
41 # The allocation data (e.g. du) for some filesystems like btrfs
42 # and zfs may not settle until the next internal sync which runs
43 # every 5s. For now, just wait unconditionally.
44 # cf. https://github.com/openzfs/zfs/issues/2134
45 path_fs = abspath(dirname(argv[0])) + '/path-fs'
46 fs = run((path_fs, opt.path), stdout=PIPE, check=True).stdout.rstrip()
47 if fs in (b'btrfs', b'zfs'):
48 sleep(5.1)
49 cmd = 'du', '-s', opt.path
50 env = environb.copy()
51 # POSIX says 512 should be the default, but for at least gnu and
52 # netbsd du, it isn't. This should cover both.
53 env[b'BLOCKSIZE'] = b'512'
54 p = run(cmd, stdout=PIPE, check=True, env=env)
55 data_size = int(p.stdout.split(maxsplit=1)[0]) * 512
56 total_size = getsize(opt.path)
57 if data_size > total_size:
58 print(0)
59 else:
60 print(total_size - data_size)
61 exit(0)
62
63 end = getsize(opt.path)
64 sparse = 0
65 with open(opt.path, 'rb') as f:
66 fd = f.fileno()
67 off = 0
68 while True:
69 new_off = lseek(fd, off, SEEK_HOLE)
70 if new_off == end:
71 break
72 off = new_off
73 try:
74 new_off = lseek(fd, off, SEEK_DATA)
75 except OSError as ex:
76 if ex.errno != ENXIO:
77 raise ex
78 if opt.verbose:
79 log(f'hole: {end - off} @ {off}\n')
80 sparse += end - off
81 break
82 if opt.verbose:
83 log(f'hole: {new_off - off} @ {off}\n')
84 sparse += new_off - off
85 off = new_off
86 print(sparse)