]> arthur.barton.de Git - bup.git/blob - lib/bup/hashsplit.py
vfs: remove dead cache_get_revlist_item()
[bup.git] / lib / bup / hashsplit.py
1
2 from __future__ import absolute_import
3 import io, math, os
4
5 from bup import _helpers, compat, helpers
6 from bup._helpers import cat_bytes
7 from bup.compat import buffer, py_maj
8 from bup.helpers import sc_page_size
9
10
11 _fmincore = getattr(helpers, 'fmincore', None)
12
13 BLOB_MAX = 8192*4   # 8192 is the "typical" blob size for bupsplit
14 BLOB_READ_SIZE = 1024*1024
15 MAX_PER_TREE = 256
16 progress_callback = None
17 fanout = 16
18
19 GIT_MODE_FILE = 0o100644
20 GIT_MODE_TREE = 0o40000
21 GIT_MODE_SYMLINK = 0o120000
22
23 # The purpose of this type of buffer is to avoid copying on peek(), get(),
24 # and eat().  We do copy the buffer contents on put(), but that should
25 # be ok if we always only put() large amounts of data at a time.
26 class Buf:
27     def __init__(self):
28         self.data = b''
29         self.start = 0
30
31     def put(self, s):
32         if s:
33             remaining = len(self.data) - self.start
34             self.data = cat_bytes(self.data, self.start, remaining,
35                                   s, 0, len(s))
36             self.start = 0
37             
38     def peek(self, count):
39         if count <= 256:
40             return self.data[self.start : self.start + count]
41         return buffer(self.data, self.start, count)
42     
43     def eat(self, count):
44         self.start += count
45
46     def get(self, count):
47         if count <= 256:
48             v = self.data[self.start : self.start + count]
49         else:
50             v = buffer(self.data, self.start, count)
51         self.start += count
52         return v
53
54     def used(self):
55         return len(self.data) - self.start
56
57
58 def _fadvise_pages_done(fd, first_page, count):
59     assert(first_page >= 0)
60     assert(count >= 0)
61     if count > 0:
62         _helpers.fadvise_done(fd,
63                               first_page * sc_page_size,
64                               count * sc_page_size)
65
66
67 def _nonresident_page_regions(status_bytes, incore_mask, max_region_len=None):
68     """Return (start_page, count) pairs in ascending start_page order for
69     each contiguous region of nonresident pages indicated by the
70     mincore() status_bytes.  Limit the number of pages in each region
71     to max_region_len."""
72     assert(max_region_len is None or max_region_len > 0)
73     start = None
74     for i, x in enumerate(status_bytes):
75         in_core = x & incore_mask
76         if start is None:
77             if not in_core:
78                 start = i
79         else:
80             count = i - start
81             if in_core:
82                 yield (start, count)
83                 start = None
84             elif max_region_len and count >= max_region_len:
85                 yield (start, count)
86                 start = i
87     if start is not None:
88         yield (start, len(status_bytes) - start)
89
90
91 def _uncache_ours_upto(fd, offset, first_region, remaining_regions):
92     """Uncache the pages of fd indicated by first_region and
93     remaining_regions that are before offset, where each region is a
94     (start_page, count) pair.  The final region must have a start_page
95     of None."""
96     rstart, rlen = first_region
97     while rstart is not None and (rstart + rlen) * sc_page_size <= offset:
98         _fadvise_pages_done(fd, rstart, rlen)
99         rstart, rlen = next(remaining_regions, (None, None))
100     return (rstart, rlen)
101
102
103 def readfile_iter(files, progress=None):
104     for filenum,f in enumerate(files):
105         ofs = 0
106         b = ''
107         fd = rpr = rstart = rlen = None
108         if _fmincore and hasattr(f, 'fileno'):
109             try:
110                 fd = f.fileno()
111             except io.UnsupportedOperation:
112                 pass
113             if fd:
114                 mcore = _fmincore(fd)
115                 if mcore:
116                     max_chunk = max(1, (8 * 1024 * 1024) / sc_page_size)
117                     rpr = _nonresident_page_regions(mcore, helpers.MINCORE_INCORE,
118                                                     max_chunk)
119                     rstart, rlen = next(rpr, (None, None))
120         while 1:
121             if progress:
122                 progress(filenum, len(b))
123             b = f.read(BLOB_READ_SIZE)
124             ofs += len(b)
125             if rpr:
126                 rstart, rlen = _uncache_ours_upto(fd, ofs, (rstart, rlen), rpr)
127             if not b:
128                 break
129             yield b
130         if rpr:
131             rstart, rlen = _uncache_ours_upto(fd, ofs, (rstart, rlen), rpr)
132
133
134 def _splitbuf(buf, basebits, fanbits):
135     while 1:
136         b = buf.peek(buf.used())
137         (ofs, bits) = _helpers.splitbuf(b)
138         if ofs:
139             if ofs > BLOB_MAX:
140                 ofs = BLOB_MAX
141                 level = 0
142             else:
143                 level = (bits-basebits)//fanbits  # integer division
144             buf.eat(ofs)
145             yield buffer(b, 0, ofs), level
146         else:
147             break
148     while buf.used() >= BLOB_MAX:
149         # limit max blob size
150         yield buf.get(BLOB_MAX), 0
151
152
153 def _hashsplit_iter(files, progress):
154     assert(BLOB_READ_SIZE > BLOB_MAX)
155     basebits = _helpers.blobbits()
156     fanbits = int(math.log(fanout or 128, 2))
157     buf = Buf()
158     for inblock in readfile_iter(files, progress):
159         buf.put(inblock)
160         for buf_and_level in _splitbuf(buf, basebits, fanbits):
161             yield buf_and_level
162     if buf.used():
163         yield buf.get(buf.used()), 0
164
165
166 def _hashsplit_iter_keep_boundaries(files, progress):
167     for real_filenum,f in enumerate(files):
168         if progress:
169             def prog(filenum, nbytes):
170                 # the inner _hashsplit_iter doesn't know the real file count,
171                 # so we'll replace it here.
172                 return progress(real_filenum, nbytes)
173         else:
174             prog = None
175         for buf_and_level in _hashsplit_iter([f], progress=prog):
176             yield buf_and_level
177
178
179 def hashsplit_iter(files, keep_boundaries, progress):
180     if keep_boundaries:
181         return _hashsplit_iter_keep_boundaries(files, progress)
182     else:
183         return _hashsplit_iter(files, progress)
184
185
186 total_split = 0
187 def split_to_blobs(makeblob, files, keep_boundaries, progress):
188     global total_split
189     for (blob, level) in hashsplit_iter(files, keep_boundaries, progress):
190         sha = makeblob(blob)
191         total_split += len(blob)
192         if progress_callback:
193             progress_callback(len(blob))
194         yield (sha, len(blob), level)
195
196
197 def _make_shalist(l):
198     ofs = 0
199     l = list(l)
200     total = sum(size for mode,sha,size, in l)
201     vlen = len(b'%x' % total)
202     shalist = []
203     for (mode, sha, size) in l:
204         shalist.append((mode, b'%0*x' % (vlen,ofs), sha))
205         ofs += size
206     assert(ofs == total)
207     return (shalist, total)
208
209
210 def _squish(maketree, stacks, n):
211     i = 0
212     while i < n or len(stacks[i]) >= MAX_PER_TREE:
213         while len(stacks) <= i+1:
214             stacks.append([])
215         if len(stacks[i]) == 1:
216             stacks[i+1] += stacks[i]
217         elif stacks[i]:
218             (shalist, size) = _make_shalist(stacks[i])
219             tree = maketree(shalist)
220             stacks[i+1].append((GIT_MODE_TREE, tree, size))
221         stacks[i] = []
222         i += 1
223
224
225 def split_to_shalist(makeblob, maketree, files,
226                      keep_boundaries, progress=None):
227     sl = split_to_blobs(makeblob, files, keep_boundaries, progress)
228     assert(fanout != 0)
229     if not fanout:
230         shal = []
231         for (sha,size,level) in sl:
232             shal.append((GIT_MODE_FILE, sha, size))
233         return _make_shalist(shal)[0]
234     else:
235         stacks = [[]]
236         for (sha,size,level) in sl:
237             stacks[0].append((GIT_MODE_FILE, sha, size))
238             _squish(maketree, stacks, level)
239         #log('stacks: %r\n' % [len(i) for i in stacks])
240         _squish(maketree, stacks, len(stacks)-1)
241         #log('stacks: %r\n' % [len(i) for i in stacks])
242         return _make_shalist(stacks[-1])[0]
243
244
245 def split_to_blob_or_tree(makeblob, maketree, files,
246                           keep_boundaries, progress=None):
247     shalist = list(split_to_shalist(makeblob, maketree,
248                                     files, keep_boundaries, progress))
249     if len(shalist) == 1:
250         return (shalist[0][0], shalist[0][2])
251     elif len(shalist) == 0:
252         return (GIT_MODE_FILE, makeblob(b''))
253     else:
254         return (GIT_MODE_TREE, maketree(shalist))
255
256
257 def open_noatime(name):
258     fd = _helpers.open_noatime(name)
259     try:
260         return os.fdopen(fd, 'rb', 1024*1024)
261     except:
262         try:
263             os.close(fd)
264         except:
265             pass
266         raise