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 # live_objs will hold on to the fd until close or exit
98 os.unlink(bloom_filename)
99 stop_at, trees_visited = None, None
100 if prune_visited_trees:
101 trees_visited = set()
102 stop_at = lambda (x): x.decode('hex') in trees_visited
103 approx_live_count = 0
104 for ref_name, ref_id in git.list_refs():
105 for item in walk_object(cat_pipe, ref_id.encode('hex'),
110 report_live_item(approx_live_count, existing_count,
111 ref_name, ref_id, item, verbosity)
112 if trees_visited is not None and item.type == 'tree':
113 trees_visited.add(item.oid)
115 if not live_objs.exists(item.oid):
116 live_objs.add(item.oid)
117 approx_live_count += 1
119 live_objs.add(item.oid)
122 log('expecting to retain about %.2f%% unnecessary objects\n'
123 % live_objs.pfalse_positive())
127 def sweep(live_objects, existing_count, cat_pipe, threshold, compression,
129 # Traverse all the packs, saving the (probably) live data.
133 def remove_stale_files(new_pack_prefix):
134 if verbosity and new_pack_prefix:
135 log('created ' + basename(new_pack_prefix) + '\n')
136 for p in ns.stale_files:
137 if new_pack_prefix and p.startswith(new_pack_prefix):
138 continue # Don't remove the new pack file
140 log('removing ' + basename(p) + '\n')
142 if ns.stale_files: # So git cat-pipe will close them
146 writer = git.PackWriter(objcache_maker=None,
147 compression_level=compression,
149 on_pack_finish=remove_stale_files)
151 # FIXME: sanity check .idx names vs .pack names?
153 for idx_name in glob.glob(os.path.join(git.repo('objects/pack'), '*.idx')):
155 qprogress('preserving live data (%d%% complete)\r'
156 % ((float(collect_count) / existing_count) * 100))
157 idx = git.open_idx(idx_name)
160 for i in xrange(0, len(idx)):
161 sha = idx.shatable[i * 20 : (i + 1) * 20]
162 if live_objects.exists(sha):
165 collect_count += idx_live_count
166 if idx_live_count == 0:
169 % git.repo_rel(basename(idx_name)))
170 ns.stale_files.append(idx_name)
171 ns.stale_files.append(idx_name[:-3] + 'pack')
174 live_frac = idx_live_count / float(len(idx))
175 if live_frac > ((100 - threshold) / 100.0):
177 log('keeping %s (%d%% live)\n' % (git.repo_rel(basename(idx_name)),
182 log('rewriting %s (%.2f%% live)\n' % (basename(idx_name),
184 for i in xrange(0, len(idx)):
185 sha = idx.shatable[i * 20 : (i + 1) * 20]
186 if live_objects.exists(sha):
187 item_it = cat_pipe.get(sha.encode('hex'))
188 _, typ, _ = next(item_it)
189 writer.just_write(sha, typ, ''.join(item_it))
191 ns.stale_files.append(idx_name)
192 ns.stale_files.append(idx_name[:-3] + 'pack')
195 progress('preserving live data (%d%% complete)\n'
196 % ((float(collect_count) / existing_count) * 100))
198 # Nothing should have recreated midx/bloom yet.
199 pack_dir = git.repo('objects/pack')
200 assert(not os.path.exists(os.path.join(pack_dir, 'bup.bloom')))
201 assert(not glob.glob(os.path.join(pack_dir, '*.midx')))
203 # try/catch should call writer.abort()?
204 # This will finally run midx.
205 writer.close() # Can only change refs (if needed) after this.
206 remove_stale_files(None) # In case we didn't write to the writer.
209 log('discarded %d%% of objects\n'
210 % ((existing_count - count_objects(pack_dir, verbosity))
211 / float(existing_count) * 100))
214 def bup_gc(threshold=10, compression=1, verbosity=0):
216 existing_count = count_objects(git.repo('objects/pack'), verbosity)
218 log('found %d objects\n' % existing_count)
219 if not existing_count:
221 log('nothing to collect\n')
224 live_objects = find_live_objects(existing_count, cat_pipe,
226 except MissingObject as ex:
227 log('bup: missing object %r \n' % ex.oid.encode('hex'))
230 # FIXME: just rename midxes and bloom, and restore them at the end if
231 # we didn't change any packs?
232 packdir = git.repo('objects/pack')
233 if verbosity: log('clearing midx files\n')
234 midx.clear_midxes(packdir)
235 if verbosity: log('clearing bloom filter\n')
236 bloom.clear_bloom(packdir)
237 if verbosity: log('clearing reflog\n')
238 expirelog_cmd = ['git', 'reflog', 'expire', '--all', '--expire=all']
239 expirelog = subprocess.Popen(expirelog_cmd, preexec_fn = git._gitenv())
240 git._git_wait(' '.join(expirelog_cmd), expirelog)
241 if verbosity: log('removing unreachable data\n')
242 sweep(live_objects, existing_count, cat_pipe,
243 threshold, compression,