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