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