1 import glob, os, subprocess, sys, tempfile
2 from bup import bloom, git, midx
3 from bup.git import MissingObject, walk_object
4 from bup.helpers import Nonlocal, log, progress, qprogress
5 from os.path import basename
7 # This garbage collector uses a Bloom filter to track the live objects
8 # during the mark phase. This means that the collection is
9 # probabilistic; it may retain some (known) percentage of garbage, but
10 # it can also work within a reasonable, fixed RAM budget for any
11 # particular percentage and repository size.
13 # The collection proceeds as follows:
15 # - Scan all live objects by walking all of the refs, and insert
16 # every hash encountered into a new Bloom "liveness" filter.
17 # Compute the size of the liveness filter based on the total
18 # number of objects in the repository. This is the "mark phase".
20 # - Clear the data that's dependent on the repository's object set,
21 # i.e. the reflog, the normal Bloom filter, and the midxes.
23 # - Traverse all of the pack files, consulting the liveness filter
24 # to decide which objects to keep.
26 # For each pack file, rewrite it iff it probably contains more
27 # than (currently) 10% garbage (computed by an initial traversal
28 # of the packfile in consultation with the liveness filter). To
29 # rewrite, traverse the packfile (again) and write each hash that
30 # tests positive against the liveness filter to a packwriter.
32 # During the traversal of all of the packfiles, delete redundant,
33 # old packfiles only after the packwriter has finished the pack
34 # that contains all of their live objects.
36 # The current code unconditionally tracks the set of tree hashes seen
37 # during the mark phase, and skips any that have already been visited.
38 # This should decrease the IO load at the cost of increased RAM use.
40 # FIXME: add a bloom filter tuning parameter?
43 def count_objects(dir, verbosity):
44 # For now we'll just use open_idx(), but we could probably be much
45 # more efficient since all we need is a single integer (the last
46 # fanout entry) from each index.
48 indexes = glob.glob(os.path.join(dir, '*.idx'))
49 for i, idx_name in enumerate(indexes):
51 log('found %d objects (%d/%d %s)\r'
52 % (object_count, i + 1, len(indexes), basename(idx_name)))
53 idx = git.open_idx(idx_name)
54 object_count += len(idx)
58 def report_live_item(n, total, ref_name, ref_id, item, verbosity):
59 status = 'scanned %02.2f%%' % (n * 100.0 / total)
60 hex_id = ref_id.encode('hex')
61 dirslash = '/' if item.type == 'tree' else ''
62 chunk_path = item.chunk_path
67 ps = '/'.join(item.path)
68 chunk_ps = '/'.join(chunk_path)
69 log('%s %s:%s/%s%s\n' % (status, hex_id, ps, chunk_ps, dirslash))
72 # Top commit, for example has none.
73 demangled = git.demangle_name(item.path[-1], item.mode)[0] if item.path \
76 # Don't print mangled paths unless the verbosity is over 3.
78 ps = '/'.join(item.path[:-1] + [demangled])
80 qprogress('%s %s:%s%s\r' % (status, hex_id, ps, dirslash))
81 elif (verbosity > 1 and item.type == 'tree') \
82 or (verbosity > 2 and item.type == 'blob'):
83 log('%s %s:%s%s\n' % (status, hex_id, ps, dirslash))
85 ps = '/'.join(item.path)
86 log('%s %s:%s%s\n' % (status, hex_id, ps, dirslash))
89 def find_live_objects(existing_count, cat_pipe, verbosity=0):
90 prune_visited_trees = True # In case we want a command line option later
91 pack_dir = git.repo('objects/pack')
92 ffd, bloom_filename = tempfile.mkstemp('.bloom', 'tmp-gc-', pack_dir)
94 # FIXME: allow selection of k?
95 # FIXME: support ephemeral bloom filters (i.e. *never* written to disk)
96 live_objs = bloom.create(bloom_filename, expected=existing_count, k=None)
97 stop_at, trees_visited = None, None
98 if prune_visited_trees:
100 stop_at = lambda (x): x.decode('hex') in trees_visited
101 approx_live_count = 0
102 for ref_name, ref_id in git.list_refs():
103 for item in walk_object(cat_pipe, ref_id.encode('hex'),
108 report_live_item(approx_live_count, existing_count,
109 ref_name, ref_id, item, verbosity)
110 bin_id = item.id.decode('hex')
111 if trees_visited is not None and item.type == 'tree':
112 trees_visited.add(bin_id)
114 if not live_objs.exists(bin_id):
115 live_objs.add(bin_id)
116 approx_live_count += 1
118 live_objs.add(bin_id)
121 log('expecting to retain about %.2f%% unnecessary objects\n'
122 % live_objs.pfalse_positive())
126 def sweep(live_objects, existing_count, cat_pipe, threshold, compression,
128 # Traverse all the packs, saving the (probably) live data.
132 def remove_stale_files(new_pack_prefix):
133 if verbosity and new_pack_prefix:
134 log('created ' + basename(new_pack_prefix) + '\n')
135 for p in ns.stale_files:
137 log('removing ' + basename(p) + '\n')
141 writer = git.PackWriter(objcache_maker=None,
142 compression_level=compression,
144 on_pack_finish=remove_stale_files)
146 # FIXME: sanity check .idx names vs .pack names?
148 for idx_name in glob.glob(os.path.join(git.repo('objects/pack'), '*.idx')):
150 qprogress('preserving live data (%d%% complete)\r'
151 % ((float(collect_count) / existing_count) * 100))
152 idx = git.open_idx(idx_name)
155 for i in xrange(0, len(idx)):
156 sha = idx.shatable[i * 20 : (i + 1) * 20]
157 if live_objects.exists(sha):
160 collect_count += idx_live_count
161 if idx_live_count == 0:
164 % git.repo_rel(basename(idx_name)))
165 ns.stale_files.append(idx_name)
166 ns.stale_files.append(idx_name[:-3] + 'pack')
169 live_frac = idx_live_count / float(len(idx))
170 if live_frac > ((100 - threshold) / 100.0):
172 log('keeping %s (%d%% live)\n' % (git.repo_rel(basename(idx_name)),
177 log('rewriting %s (%.2f%% live)\n' % (basename(idx_name),
179 for i in xrange(0, len(idx)):
180 sha = idx.shatable[i * 20 : (i + 1) * 20]
181 if live_objects.exists(sha):
182 item_it = cat_pipe.get(sha.encode('hex'))
183 type = item_it.next()
184 writer.just_write(sha, type, ''.join(item_it))
186 ns.stale_files.append(idx_name)
187 ns.stale_files.append(idx_name[:-3] + 'pack')
190 progress('preserving live data (%d%% complete)\n'
191 % ((float(collect_count) / existing_count) * 100))
193 # Nothing should have recreated midx/bloom yet.
194 pack_dir = git.repo('objects/pack')
195 assert(not os.path.exists(os.path.join(pack_dir, 'bup.bloom')))
196 assert(not glob.glob(os.path.join(pack_dir, '*.midx')))
198 # try/catch should call writer.abort()?
199 # This will finally run midx.
200 writer.close() # Can only change refs (if needed) after this.
201 remove_stale_files(None) # In case we didn't write to the writer.
204 log('discarded %d%% of objects\n'
205 % ((existing_count - count_objects(pack_dir, verbosity))
206 / float(existing_count) * 100))
209 def bup_gc(threshold=10, compression=1, verbosity=0):
211 existing_count = count_objects(git.repo('objects/pack'), verbosity)
213 log('found %d objects\n' % existing_count)
214 if not existing_count:
216 log('nothing to collect\n')
219 live_objects = find_live_objects(existing_count, cat_pipe,
221 except MissingObject as ex:
222 log('bup: missing object %r \n' % ex.id.encode('hex'))
225 # FIXME: just rename midxes and bloom, and restore them at the end if
226 # we didn't change any packs?
227 if verbosity: log('clearing midx files\n')
229 if verbosity: log('clearing bloom filter\n')
230 bloom.clear_bloom(git.repo('objects/pack'))
231 if verbosity: log('clearing reflog\n')
232 expirelog_cmd = ['git', 'reflog', 'expire', '--all', '--expire=all']
233 expirelog = subprocess.Popen(expirelog_cmd, preexec_fn = git._gitenv())
234 git._git_wait(' '.join(expirelog_cmd), expirelog)
235 if verbosity: log('removing unreachable data\n')
236 sweep(live_objects, existing_count, cat_pipe,
237 threshold, compression,
241 os.unlink(live_objects.name)