]> arthur.barton.de Git - bup.git/blob - cmd/bloom-cmd.py
compat.hexstr: add and use
[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):
63     global _first
64     b = None
65     if os.path.exists(outfilename) and not opt.force:
66         b = bloom.ShaBloom(outfilename)
67         if not b.valid():
68             debug1("bloom: Existing invalid bloom found, regenerating.\n")
69             b = None
70
71     add = []
72     rest = []
73     add_count = 0
74     rest_count = 0
75     for i,name in enumerate(glob.glob('%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     total = add_count + rest_count
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 (b.bits < bloom.MAX_BLOOM_BITS and
97               b.pfalse_positive(add_count) > bloom.MAX_PFALSE_POSITIVE):
98             debug1("bloom: regenerating: adding %d entries gives "
99                    "%.2f%% false positives.\n"
100                    % (add_count, b.pfalse_positive(add_count)))
101             b = None
102         else:
103             b = bloom.ShaBloom(outfilename, readwrite=True, expected=add_count)
104     if not b: # Need all idxs to build from scratch
105         add += rest
106         add_count += rest_count
107     del rest
108     del rest_count
109
110     msg = b is None and 'creating from' or 'adding'
111     if not _first: _first = path
112     dirprefix = (_first != path) and git.repo_rel(path)+': ' or ''
113     progress('bloom: %s%s %d file%s (%d object%s).\r'
114         % (dirprefix, msg,
115            len(add), len(add)!=1 and 's' or '',
116            add_count, add_count!=1 and 's' or ''))
117
118     tfname = None
119     if b is None:
120         tfname = os.path.join(path, 'bup.tmp.bloom')
121         b = bloom.create(tfname, expected=add_count, k=opt.k)
122     count = 0
123     icount = 0
124     for name in add:
125         ix = git.open_idx(name)
126         qprogress('bloom: writing %.2f%% (%d/%d objects)\r' 
127                   % (icount*100.0/add_count, icount, add_count))
128         b.add_idx(ix)
129         count += 1
130         icount += len(ix)
131
132     # Currently, there's an open file object for tfname inside b.
133     # Make sure it's closed before rename.
134     b.close()
135
136     if tfname:
137         os.rename(tfname, outfilename)
138
139
140 handle_ctrl_c()
141
142 o = options.Options(optspec)
143 (opt, flags, extra) = o.parse(sys.argv[1:])
144
145 if extra:
146     o.fatal('no positional parameters expected')
147
148 git.check_repo_or_die()
149
150 if not opt.check and opt.k and opt.k not in (4,5):
151     o.fatal('only k values of 4 and 5 are supported')
152
153 paths = opt.dir and [opt.dir] or git.all_packdirs()
154 for path in paths:
155     debug1('bloom: scanning %s\n' % path)
156     outfilename = opt.output or os.path.join(path, 'bup.bloom')
157     if opt.check:
158         check_bloom(path, outfilename, opt.check)
159     elif opt.ruin:
160         ruin_bloom(outfilename)
161     else:
162         do_bloom(path, outfilename)
163
164 if saved_errors:
165     log('WARNING: %d errors encountered during bloom.\n' % len(saved_errors))
166     sys.exit(1)
167 elif opt.check:
168     log('All tests passed.\n')