]> arthur.barton.de Git - bup.git/blob - cmd/bloom-cmd.py
Use absolute_import from the __future__ everywhere
[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.helpers import (add_error, debug1, handle_ctrl_c, log, progress, qprogress,
13                          saved_errors)
14
15 optspec = """
16 bup bloom [options...]
17 --
18 ruin       ruin the specified bloom file (clearing the bitfield)
19 f,force    ignore existing bloom file and regenerate it from scratch
20 o,output=  output bloom filename (default: auto)
21 d,dir=     input directory to look for idx files (default: auto)
22 k,hashes=  number of hash functions to use (4 or 5) (default: auto)
23 c,check=   check the given .idx file against the bloom filter
24 """
25
26
27 def ruin_bloom(bloomfilename):
28     rbloomfilename = git.repo_rel(bloomfilename)
29     if not os.path.exists(bloomfilename):
30         log("%s\n" % bloomfilename)
31         add_error("bloom: %s not found to ruin\n" % rbloomfilename)
32         return
33     b = bloom.ShaBloom(bloomfilename, readwrite=True, expected=1)
34     b.map[16:16+2**b.bits] = '\0' * 2**b.bits
35
36
37 def check_bloom(path, bloomfilename, idx):
38     rbloomfilename = git.repo_rel(bloomfilename)
39     ridx = git.repo_rel(idx)
40     if not os.path.exists(bloomfilename):
41         log("bloom: %s: does not exist.\n" % rbloomfilename)
42         return
43     b = bloom.ShaBloom(bloomfilename)
44     if not b.valid():
45         add_error("bloom: %r is invalid.\n" % rbloomfilename)
46         return
47     base = os.path.basename(idx)
48     if base not in b.idxnames:
49         log("bloom: %s does not contain the idx.\n" % rbloomfilename)
50         return
51     if base == idx:
52         idx = os.path.join(path, idx)
53     log("bloom: bloom file: %s\n" % rbloomfilename)
54     log("bloom:   checking %s\n" % ridx)
55     for objsha in git.open_idx(idx):
56         if not b.exists(objsha):
57             add_error("bloom: ERROR: object %s missing" 
58                       % str(objsha).encode('hex'))
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')