]> arthur.barton.de Git - bup.git/blob - cmd/bloom-cmd.py
midx: shun buffers
[bup.git] / cmd / bloom-cmd.py
1 #!/bin/sh
2 """": # -*-python-*-
3 bup_python="$(dirname "$0")/bup-python" || exit $?
4 exec "$bup_python" "$0" ${1+"$@"}
5 """
6 # end of bup preamble
7
8 from __future__ import absolute_import
9 import glob, os, sys, tempfile
10
11 from bup import options, git, bloom
12 from bup.compat import hexstr
13 from bup.helpers import (add_error, debug1, handle_ctrl_c, log, progress, qprogress,
14                          saved_errors)
15
16 optspec = """
17 bup bloom [options...]
18 --
19 ruin       ruin the specified bloom file (clearing the bitfield)
20 f,force    ignore existing bloom file and regenerate it from scratch
21 o,output=  output bloom filename (default: auto)
22 d,dir=     input directory to look for idx files (default: auto)
23 k,hashes=  number of hash functions to use (4 or 5) (default: auto)
24 c,check=   check the given .idx file against the bloom filter
25 """
26
27
28 def ruin_bloom(bloomfilename):
29     rbloomfilename = git.repo_rel(bloomfilename)
30     if not os.path.exists(bloomfilename):
31         log("%s\n" % bloomfilename)
32         add_error("bloom: %s not found to ruin\n" % rbloomfilename)
33         return
34     b = bloom.ShaBloom(bloomfilename, readwrite=True, expected=1)
35     b.map[16:16+2**b.bits] = '\0' * 2**b.bits
36
37
38 def check_bloom(path, bloomfilename, idx):
39     rbloomfilename = git.repo_rel(bloomfilename)
40     ridx = git.repo_rel(idx)
41     if not os.path.exists(bloomfilename):
42         log("bloom: %s: does not exist.\n" % rbloomfilename)
43         return
44     b = bloom.ShaBloom(bloomfilename)
45     if not b.valid():
46         add_error("bloom: %r is invalid.\n" % rbloomfilename)
47         return
48     base = os.path.basename(idx)
49     if base not in b.idxnames:
50         log("bloom: %s does not contain the idx.\n" % rbloomfilename)
51         return
52     if base == idx:
53         idx = os.path.join(path, idx)
54     log("bloom: bloom file: %s\n" % rbloomfilename)
55     log("bloom:   checking %s\n" % ridx)
56     for objsha in git.open_idx(idx):
57         if not b.exists(objsha):
58             add_error('bloom: ERROR: object %s missing' % hexstr(objsha))
59
60
61 _first = None
62 def do_bloom(path, outfilename, k):
63     global _first
64     assert k in (None, 4, 5)
65     b = None
66     if os.path.exists(outfilename) and not opt.force:
67         b = bloom.ShaBloom(outfilename)
68         if not b.valid():
69             debug1("bloom: Existing invalid bloom found, regenerating.\n")
70             b = None
71
72     add = []
73     rest = []
74     add_count = 0
75     rest_count = 0
76     for i,name in enumerate(glob.glob('%s/*.idx' % path)):
77         progress('bloom: counting: %d\r' % i)
78         ix = git.open_idx(name)
79         ixbase = os.path.basename(name)
80         if b and (ixbase in b.idxnames):
81             rest.append(name)
82             rest_count += len(ix)
83         else:
84             add.append(name)
85             add_count += len(ix)
86
87     if not add:
88         debug1("bloom: nothing to do.\n")
89         return
90
91     if b:
92         if len(b) != rest_count:
93             debug1("bloom: size %d != idx total %d, regenerating\n"
94                    % (len(b), rest_count))
95             b = None
96         elif k is not None and k != b.k:
97             debug1("bloom: new k %d != existing k %d, regenerating\n"
98                    % (k, b.k))
99             b = None
100         elif (b.bits < bloom.MAX_BLOOM_BITS[b.k] and
101               b.pfalse_positive(add_count) > bloom.MAX_PFALSE_POSITIVE):
102             debug1("bloom: regenerating: adding %d entries gives "
103                    "%.2f%% false positives.\n"
104                    % (add_count, b.pfalse_positive(add_count)))
105             b = None
106         else:
107             b = bloom.ShaBloom(outfilename, readwrite=True, expected=add_count)
108     if not b: # Need all idxs to build from scratch
109         add += rest
110         add_count += rest_count
111     del rest
112     del rest_count
113
114     msg = b is None and 'creating from' or 'adding'
115     if not _first: _first = path
116     dirprefix = (_first != path) and git.repo_rel(path)+': ' or ''
117     progress('bloom: %s%s %d file%s (%d object%s).\r'
118         % (dirprefix, msg,
119            len(add), len(add)!=1 and 's' or '',
120            add_count, add_count!=1 and 's' or ''))
121
122     tfname = None
123     if b is None:
124         tfname = os.path.join(path, 'bup.tmp.bloom')
125         b = bloom.create(tfname, expected=add_count, k=k)
126     count = 0
127     icount = 0
128     for name in add:
129         ix = git.open_idx(name)
130         qprogress('bloom: writing %.2f%% (%d/%d objects)\r' 
131                   % (icount*100.0/add_count, icount, add_count))
132         b.add_idx(ix)
133         count += 1
134         icount += len(ix)
135
136     # Currently, there's an open file object for tfname inside b.
137     # Make sure it's closed before rename.
138     b.close()
139
140     if tfname:
141         os.rename(tfname, outfilename)
142
143
144 handle_ctrl_c()
145
146 o = options.Options(optspec)
147 (opt, flags, extra) = o.parse(sys.argv[1:])
148
149 if extra:
150     o.fatal('no positional parameters expected')
151
152 git.check_repo_or_die()
153
154 if not opt.check and opt.k and opt.k not in (4,5):
155     o.fatal('only k values of 4 and 5 are supported')
156
157 paths = opt.dir and [opt.dir] or git.all_packdirs()
158 for path in paths:
159     debug1('bloom: scanning %s\n' % path)
160     outfilename = opt.output or os.path.join(path, 'bup.bloom')
161     if opt.check:
162         check_bloom(path, outfilename, opt.check)
163     elif opt.ruin:
164         ruin_bloom(outfilename)
165     else:
166         do_bloom(path, outfilename, opt.k)
167
168 if saved_errors:
169     log('WARNING: %d errors encountered during bloom.\n' % len(saved_errors))
170     sys.exit(1)
171 elif opt.check:
172     log('All tests passed.\n')