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