]> arthur.barton.de Git - bup.git/blob - cmd/midx-cmd.py
client.py,git.py: run 'bup midx -a' automatically sometimes.
[bup.git] / cmd / midx-cmd.py
1 #!/usr/bin/env python
2 import sys, math, struct, glob, resource
3 from bup import options, git
4 from bup.helpers import *
5
6 PAGE_SIZE=4096
7 SHA_PER_PAGE=PAGE_SIZE/20.
8
9 optspec = """
10 bup midx [options...] <idxnames...>
11 --
12 o,output=  output midx filename (default: auto-generated)
13 a,auto     automatically create .midx from any unindexed .idx files
14 f,force    automatically create .midx from *all* .idx files
15 max-files= maximum number of idx files to open at once [-1]
16 dir=       directory containing idx/midx files
17 """
18
19 def _group(l, count):
20     for i in xrange(0, len(l), count):
21         yield l[i:i+count]
22         
23         
24 def max_files():
25     mf = min(resource.getrlimit(resource.RLIMIT_NOFILE))
26     if mf > 32:
27         mf -= 20  # just a safety margin
28     else:
29         mf -= 6   # minimum safety margin
30     return mf
31
32
33 def merge(idxlist, bits, table):
34     count = 0
35     for e in git.idxmerge(idxlist):
36         count += 1
37         prefix = git.extract_bits(e, bits)
38         table[prefix] = count
39         yield e
40
41
42 def _do_midx(outdir, outfilename, infilenames):
43     if not outfilename:
44         assert(outdir)
45         sum = Sha1('\0'.join(infilenames)).hexdigest()
46         outfilename = '%s/midx-%s.midx' % (outdir, sum)
47     
48     inp = []
49     total = 0
50     allfilenames = {}
51     for name in infilenames:
52         ix = git.open_idx(name)
53         for n in ix.idxnames:
54             allfilenames[n] = 1
55         inp.append(ix)
56         total += len(ix)
57
58     log('Merging %d indexes (%d objects).\n' % (len(infilenames), total))
59     if (not opt.force and (total < 1024 and len(infilenames) < 3)) \
60        or len(infilenames) < 2 \
61        or (opt.force and not total):
62         log('midx: nothing to do.\n')
63         return
64
65     pages = int(total/SHA_PER_PAGE) or 1
66     bits = int(math.ceil(math.log(pages, 2)))
67     entries = 2**bits
68     log('Table size: %d (%d bits)\n' % (entries*4, bits))
69     
70     table = [0]*entries
71
72     try:
73         os.unlink(outfilename)
74     except OSError:
75         pass
76     f = open(outfilename + '.tmp', 'w+')
77     f.write('MIDX\0\0\0\2')
78     f.write(struct.pack('!I', bits))
79     assert(f.tell() == 12)
80     f.write('\0'*4*entries)
81     
82     for e in merge(inp, bits, table):
83         f.write(e)
84         
85     f.write('\0'.join(os.path.basename(p) for p in allfilenames.keys()))
86
87     f.seek(12)
88     f.write(struct.pack('!%dI' % entries, *table))
89     f.close()
90     os.rename(outfilename + '.tmp', outfilename)
91
92     # this is just for testing
93     if 0:
94         p = git.PackMidx(outfilename)
95         assert(len(p.idxnames) == len(infilenames))
96         print p.idxnames
97         assert(len(p) == total)
98         pi = iter(p)
99         for i in merge(inp, total, bits, table):
100             assert(i == pi.next())
101             assert(p.exists(i))
102
103     return total,outfilename
104
105
106 def do_midx(outdir, outfilename, infilenames):
107     rv = _do_midx(outdir, outfilename, infilenames)
108     if rv:
109         print rv[1]
110
111
112 def do_midx_dir(path):
113     already = {}
114     sizes = {}
115     if opt.force and not opt.auto:
116         midxs = []   # don't use existing midx files
117     else:
118         midxs = glob.glob('%s/*.midx' % path)
119         contents = {}
120         for mname in midxs:
121             m = git.open_idx(mname)
122             contents[mname] = [('%s/%s' % (path,i)) for i in m.idxnames]
123             sizes[mname] = len(m)
124                     
125         # sort the biggest midxes first, so that we can eliminate smaller
126         # redundant ones that come later in the list
127         midxs.sort(lambda x,y: -cmp(sizes[x], sizes[y]))
128         
129         for mname in midxs:
130             any = 0
131             for iname in contents[mname]:
132                 if not already.get(iname):
133                     already[iname] = 1
134                     any = 1
135             if not any:
136                 log('%r is redundant\n' % mname)
137                 unlink(mname)
138                 already[mname] = 1
139
140     midxs = [k for k in midxs if not already.get(k)]
141     idxs = [k for k in glob.glob('%s/*.idx' % path) if not already.get(k)]
142
143     for iname in idxs:
144         i = git.open_idx(iname)
145         sizes[iname] = len(i)
146
147     all = [(sizes[n],n) for n in (midxs + idxs)]
148     
149     # FIXME: what are the optimal values?  Does this make sense?
150     DESIRED_HWM = opt.force and 1 or 5
151     DESIRED_LWM = opt.force and 1 or 2
152     existed = dict((name,1) for sz,name in all)
153     log('midx: %d indexes; want no more than %d.\n' % (len(all), DESIRED_HWM))
154     if len(all) <= DESIRED_HWM:
155         log('midx: nothing to do.\n')
156     while len(all) > DESIRED_HWM:
157         all.sort()
158         part1 = [name for sz,name in all[:len(all)-DESIRED_LWM+1]]
159         part2 = all[len(all)-DESIRED_LWM+1:]
160         all = list(do_midx_group(path, part1)) + part2
161         if len(all) > DESIRED_HWM:
162             log('\nStill too many indexes (%d > %d).  Merging again.\n'
163                 % (len(all), DESIRED_HWM))
164
165     for sz,name in all:
166         if not existed.get(name):
167             print name
168
169
170 def do_midx_group(outdir, infiles):
171     for sublist in _group(infiles, opt.max_files):
172         rv = _do_midx(path, None, sublist)
173         if rv:
174             yield rv
175
176
177
178 o = options.Options('bup midx', optspec)
179 (opt, flags, extra) = o.parse(sys.argv[1:])
180
181 if extra and (opt.auto or opt.force):
182     o.fatal("you can't use -f/-a and also provide filenames")
183
184 git.check_repo_or_die()
185
186 if opt.max_files < 0:
187     opt.max_files = max_files()
188 assert(opt.max_files >= 5)
189
190 if extra:
191     do_midx(git.repo('objects/pack'), opt.output, extra)
192 elif opt.auto or opt.force:
193     if opt.dir:
194         paths = [opt.dir]
195     else:
196         paths = [git.repo('objects/pack')]
197         paths += glob.glob(git.repo('index-cache/*/.'))
198     for path in paths:
199         log('midx: scanning %s\n' % path)
200         do_midx_dir(path)
201         log('\n')
202 else:
203     o.fatal("you must use -f or -a or provide input filenames")