Debian Codegraph @

hgext/remotefilelog/basepack.py

raw
1 from __future__ import annotations
2
3 import collections
4 import errno
5 import mmap
6 import os
7 import struct
8 import time
9
10 from mercurial.i18n import _
11 from mercurial.node import hex
12 from mercurial import (
13 policy,
14 util,
15 vfs as vfsmod,
16 )
17 from mercurial.utils import hashutil
18 from . import shallowutil
19
20 osutil = policy.importmod('osutil')
21
22 # The pack version supported by this implementation. This will need to be
23 # rev'd whenever the byte format changes. Ex: changing the fanout prefix,
24 # changing any of the int sizes, changing the delta algorithm, etc.
25 PACKVERSIONSIZE = 1
26 INDEXVERSIONSIZE = 2
27
28 FANOUTSTART = INDEXVERSIONSIZE
29
30 # Constant that indicates a fanout table entry hasn't been filled in. (This does
31 # not get serialized)
32 EMPTYFANOUT = -1
33
34 # The fanout prefix is the number of bytes that can be addressed by the fanout
35 # table. Example: a fanout prefix of 1 means we use the first byte of a hash to
36 # look in the fanout table (which will be 2^8 entries long).
37 SMALLFANOUTPREFIX = 1
38 LARGEFANOUTPREFIX = 2
39
40 # The number of entries in the index at which point we switch to a large fanout.
41 # It is chosen to balance the linear scan through a sparse fanout, with the
42 # size of the bisect in actual index.
43 # 2^16 / 8 was chosen because it trades off (1 step fanout scan + 5 step
44 # bisect) with (8 step fanout scan + 1 step bisect)
45 # 5 step bisect = log(2^16 / 8 / 255) # fanout
46 # 10 step fanout scan = 2^16 / (2^16 / 8) # fanout space divided by entries
47 SMALLFANOUTCUTOFF = 2**16 // 8
48
49 # The amount of time to wait between checking for new packs. This prevents an
50 # exception when data is moved to a new pack after the process has already
51 # loaded the pack list.
52 REFRESHRATE = 0.1
53
54
55 class _cachebackedpacks:
56 def __init__(self, packs, cachesize):
57 self._packs = set(packs)
58 self._lrucache = util.lrucachedict(cachesize)
59 self._lastpack = None
60
61 # Avoid cold start of the cache by populating the most recent packs
62 # in the cache.
63 for i in reversed(range(min(cachesize, len(packs)))):
64 self._movetofront(packs[i])
65
66 def _movetofront(self, pack):
67 # This effectively makes pack the first entry in the cache.
68 self._lrucache[pack] = True
69
70 def _registerlastpackusage(self):
71 if self._lastpack is not None:
72 self._movetofront(self._lastpack)
73 self._lastpack = None
74
75 def add(self, pack):
76 self._registerlastpackusage()
77
78 # This method will mostly be called when packs are not in cache.
79 # Therefore, adding pack to the cache.
80 self._movetofront(pack)
81 self._packs.add(pack)
82
83 def __iter__(self):
84 self._registerlastpackusage()
85
86 # Cache iteration is based on LRU.
87 for pack in self._lrucache:
88 self._lastpack = pack
89 yield pack
90
91 cachedpacks = {pack for pack in self._lrucache}
92 # Yield for paths not in the cache.
93 for pack in self._packs - cachedpacks:
94 self._lastpack = pack
95 yield pack
96
97 # Data not found in any pack.
98 self._lastpack = None
99
100
101 class basepackstore:
102 # Default cache size limit for the pack files.
103 DEFAULTCACHESIZE = 100
104
105 def __init__(self, ui, path):
106 self.ui = ui
107 self.path = path
108
109 # lastrefesh is 0 so we'll immediately check for new packs on the first
110 # failure.
111 self.lastrefresh = 0
112
113 packs = []
114 for filepath, __, __ in self._getavailablepackfilessorted():
115 try:
116 pack = self.getpack(filepath)
117 except Exception as ex:
118 # An exception may be thrown if the pack file is corrupted
119 # somehow. Log a warning but keep going in this case, just
120 # skipping this pack file.
121 #
122 # If this is an ENOENT error then don't even bother logging.
123 # Someone could have removed the file since we retrieved the
124 # list of paths.
125 if getattr(ex, 'errno', None) != errno.ENOENT:
126 ui.warn(_(b'unable to load pack %s: %s\n') % (filepath, ex))
127 continue
128 packs.append(pack)
129
130 self.packs = _cachebackedpacks(packs, self.DEFAULTCACHESIZE)
131
132 def _getavailablepackfiles(self):
133 """For each pack file (a index/data file combo), yields:
134 (full path without extension, mtime, size)
135
136 mtime will be the mtime of the index/data file (whichever is newer)
137 size is the combined size of index/data file
138 """
139 indexsuffixlen = len(self.INDEXSUFFIX)
140 packsuffixlen = len(self.PACKSUFFIX)
141
142 ids = set()
143 sizes = collections.defaultdict(int)
144 mtimes = collections.defaultdict(list)
145 try:
146 for filename, type, stat in osutil.listdir(self.path, stat=True):
147 id = None
148 if filename[-indexsuffixlen:] == self.INDEXSUFFIX:
149 id = filename[:-indexsuffixlen]
150 elif filename[-packsuffixlen:] == self.PACKSUFFIX:
151 id = filename[:-packsuffixlen]
152
153 # Since we expect to have two files corresponding to each ID
154 # (the index file and the pack file), we can yield once we see
155 # it twice.
156 if id:
157 sizes[id] += stat.st_size # Sum both files' sizes together
158 mtimes[id].append(stat.st_mtime)
159 if id in ids:
160 yield (
161 os.path.join(self.path, id),
162 max(mtimes[id]),
163 sizes[id],
164 )
165 else:
166 ids.add(id)
167 except FileNotFoundError:
168 pass
169
170 def _getavailablepackfilessorted(self):
171 """Like `_getavailablepackfiles`, but also sorts the files by mtime,
172 yielding newest files first.
173
174 This is desirable, since it is more likely newer packfiles have more
175 desirable data.
176 """
177 files = []
178 for path, mtime, size in self._getavailablepackfiles():
179 files.append((mtime, size, path))
180 files = sorted(files, reverse=True)
181 for mtime, size, path in files:
182 yield path, mtime, size
183
184 def gettotalsizeandcount(self):
185 """Returns the total disk size (in bytes) of all the pack files in
186 this store, and the count of pack files.
187
188 (This might be smaller than the total size of the ``self.path``
189 directory, since this only considers fuly-writen pack files, and not
190 temporary files or other detritus on the directory.)
191 """
192 totalsize = 0
193 count = 0
194 for __, __, size in self._getavailablepackfiles():
195 totalsize += size
196 count += 1
197 return totalsize, count
198
199 def getmetrics(self):
200 """Returns metrics on the state of this store."""
201 size, count = self.gettotalsizeandcount()
202 return {
203 b'numpacks': count,
204 b'totalpacksize': size,
205 }
206
207 def getpack(self, path):
208 raise NotImplementedError()
209
210 def getmissing(self, keys):
211 missing = keys
212 for pack in self.packs:
213 missing = pack.getmissing(missing)
214
215 # Ensures better performance of the cache by keeping the most
216 # recently accessed pack at the beginning in subsequent iterations.
217 if not missing:
218 return missing
219
220 if missing:
221 for pack in self.refresh():
222 missing = pack.getmissing(missing)
223
224 return missing
225
226 def markledger(self, ledger, options=None):
227 for pack in self.packs:
228 pack.markledger(ledger)
229
230 def markforrefresh(self):
231 """Tells the store that there may be new pack files, so the next time it
232 has a lookup miss it should check for new files."""
233 self.lastrefresh = 0
234
235 def refresh(self):
236 """Checks for any new packs on disk, adds them to the main pack list,
237 and returns a list of just the new packs."""
238 now = time.time()
239
240 # If we experience a lot of misses (like in the case of getmissing() on
241 # new objects), let's only actually check disk for new stuff every once
242 # in a while. Generally this code path should only ever matter when a
243 # repack is going on in the background, and that should be pretty rare
244 # to have that happen twice in quick succession.
245 newpacks = []
246 if now > self.lastrefresh + REFRESHRATE:
247 self.lastrefresh = now
248 previous = {p.path for p in self.packs}
249 for filepath, __, __ in self._getavailablepackfilessorted():
250 if filepath not in previous:
251 newpack = self.getpack(filepath)
252 newpacks.append(newpack)
253 self.packs.add(newpack)
254
255 return newpacks
256
257
258 class versionmixin:
259 # Mix-in for classes with multiple supported versions
260 VERSION = None
261 SUPPORTED_VERSIONS = [2]
262
263 def _checkversion(self, version):
264 if version in self.SUPPORTED_VERSIONS:
265 if self.VERSION is None:
266 # only affect this instance
267 self.VERSION = version
268 elif self.VERSION != version:
269 raise RuntimeError(b'inconsistent version: %d' % version)
270 else:
271 raise RuntimeError(b'unsupported version: %d' % version)
272
273
274 class basepack(versionmixin):
275 # The maximum amount we should read via mmap before remmaping so the old
276 # pages can be released (100MB)
277 MAXPAGEDIN = 100 * 1024**2
278
279 SUPPORTED_VERSIONS = [2]
280
281 PACKSUFFIX: bytes
282 INDEXSUFFIX: bytes
283 _pagedin: int
284
285 def __init__(self, path):
286 self.path = path
287 self.packpath = path + self.PACKSUFFIX
288 self.indexpath = path + self.INDEXSUFFIX
289
290 self.indexsize = os.stat(self.indexpath).st_size
291 self.datasize = os.stat(self.packpath).st_size
292
293 self._index = None
294 self._data = None
295 self.freememory() # initialize the mmap
296
297 version = struct.unpack(b'!B', self._data[:PACKVERSIONSIZE])[0]
298 self._checkversion(version)
299
300 version, config = struct.unpack(b'!BB', self._index[:INDEXVERSIONSIZE])
301 self._checkversion(version)
302
303 if 0b10000000 & config:
304 self.params = indexparams(LARGEFANOUTPREFIX, version)
305 else:
306 self.params = indexparams(SMALLFANOUTPREFIX, version)
307
308 @util.propertycache
309 def _fanouttable(self):
310 params = self.params
311 rawfanout = self._index[FANOUTSTART : FANOUTSTART + params.fanoutsize]
312 fanouttable = []
313 for i in range(0, params.fanoutcount):
314 loc = i * 4
315 fanoutentry = struct.unpack(b'!I', rawfanout[loc : loc + 4])[0]
316 fanouttable.append(fanoutentry)
317 return fanouttable
318
319 @util.propertycache
320 def _indexend(self):
321 nodecount = struct.unpack_from(
322 b'!Q', self._index, self.params.indexstart - 8
323 )[0]
324 return self.params.indexstart + nodecount * self.INDEXENTRYLENGTH
325
326 def freememory(self):
327 """Unmap and remap the memory to free it up after known expensive
328 operations. Return True if self._data and self._index were reloaded.
329 """
330 if self._index:
331 if self._pagedin < self.MAXPAGEDIN:
332 return False
333
334 self._index.close()
335 self._data.close()
336
337 # TODO: use an opener/vfs to access these paths
338 with open(self.indexpath, 'rb') as indexfp:
339 # memory-map the file, size 0 means whole file
340 self._index = mmap.mmap(
341 indexfp.fileno(), 0, access=mmap.ACCESS_READ
342 )
343 with open(self.packpath, 'rb') as datafp:
344 self._data = mmap.mmap(datafp.fileno(), 0, access=mmap.ACCESS_READ)
345
346 self._pagedin = 0
347 return True
348
349 def getmissing(self, keys):
350 raise NotImplementedError()
351
352 def markledger(self, ledger, options=None):
353 raise NotImplementedError()
354
355 def cleanup(self, ledger):
356 raise NotImplementedError()
357
358 def __iter__(self):
359 raise NotImplementedError()
360
361 def iterentries(self):
362 raise NotImplementedError()
363
364
365 class mutablebasepack(versionmixin):
366 INDEXENTRYLENGTH: int
367 PACKSUFFIX: bytes
368 INDEXSUFFIX: bytes
369
370 def __init__(self, ui, packdir, version=2):
371 self._checkversion(version)
372 # TODO(augie): make this configurable
373 self._compressor = b'GZ'
374 opener = vfsmod.vfs(packdir)
375 opener.createmode = 0o444
376 self.opener = opener
377
378 self.entries = {}
379
380 shallowutil.mkstickygroupdir(ui, packdir)
381 self.packfp, self.packpath = opener.mkstemp(
382 suffix=self.PACKSUFFIX + b'-tmp'
383 )
384 self.idxfp, self.idxpath = opener.mkstemp(
385 suffix=self.INDEXSUFFIX + b'-tmp'
386 )
387 self.packfp = os.fdopen(self.packfp, 'wb+')
388 self.idxfp = os.fdopen(self.idxfp, 'wb+')
389 self.sha = hashutil.sha1()
390 self._closed = False
391
392 # The opener provides no way of doing permission fixup on files created
393 # via mkstemp, so we must fix it ourselves. We can probably fix this
394 # upstream in vfs.mkstemp so we don't need to use the private method.
395 opener._fixfilemode(opener.join(self.packpath))
396 opener._fixfilemode(opener.join(self.idxpath))
397
398 # Write header
399 # TODO: make it extensible (ex: allow specifying compression algorithm,
400 # a flexible key/value header, delta algorithm, fanout size, etc)
401 versionbuf = struct.pack(b'!B', self.VERSION) # unsigned 1 byte int
402 self.writeraw(versionbuf)
403
404 def __enter__(self):
405 return self
406
407 def __exit__(self, exc_type, exc_value, traceback):
408 if exc_type is None:
409 self.close()
410 else:
411 self.abort()
412
413 def abort(self):
414 # Unclean exit
415 self._cleantemppacks()
416
417 def writeraw(self, data):
418 self.packfp.write(data)
419 self.sha.update(data)
420
421 def close(self, ledger=None):
422 if self._closed:
423 return
424
425 try:
426 sha = hex(self.sha.digest())
427 self.packfp.close()
428 self.writeindex()
429
430 if len(self.entries) == 0:
431 # Empty pack
432 self._cleantemppacks()
433 self._closed = True
434 return None
435
436 self.opener.rename(self.packpath, sha + self.PACKSUFFIX)
437 try:
438 self.opener.rename(self.idxpath, sha + self.INDEXSUFFIX)
439 except Exception as ex:
440 try:
441 self.opener.unlink(sha + self.PACKSUFFIX)
442 except Exception:
443 pass
444 # Throw exception 'ex' explicitly since a normal 'raise' would
445 # potentially throw an exception from the unlink cleanup.
446 raise ex
447 except Exception:
448 # Clean up temp packs in all exception cases
449 self._cleantemppacks()
450 raise
451
452 self._closed = True
453 result = self.opener.join(sha)
454 if ledger:
455 ledger.addcreated(result)
456 return result
457
458 def _cleantemppacks(self):
459 try:
460 self.opener.unlink(self.packpath)
461 except Exception:
462 pass
463 try:
464 self.opener.unlink(self.idxpath)
465 except Exception:
466 pass
467
468 def writeindex(self):
469 largefanout = len(self.entries) > SMALLFANOUTCUTOFF
470 if largefanout:
471 params = indexparams(LARGEFANOUTPREFIX, self.VERSION)
472 else:
473 params = indexparams(SMALLFANOUTPREFIX, self.VERSION)
474
475 fanouttable = [EMPTYFANOUT] * params.fanoutcount
476
477 # Precompute the location of each entry
478 locations = {}
479 count = 0
480 for node in sorted(self.entries):
481 location = count * self.INDEXENTRYLENGTH
482 locations[node] = location
483 count += 1
484
485 # Must use [0] on the unpack result since it's always a tuple.
486 fanoutkey = struct.unpack(
487 params.fanoutstruct, node[: params.fanoutprefix]
488 )[0]
489 if fanouttable[fanoutkey] == EMPTYFANOUT:
490 fanouttable[fanoutkey] = location
491
492 rawfanouttable = b''
493 last = 0
494 for offset in fanouttable:
495 offset = offset if offset != EMPTYFANOUT else last
496 last = offset
497 rawfanouttable += struct.pack(b'!I', offset)
498
499 rawentrieslength = struct.pack(b'!Q', len(self.entries))
500
501 # The index offset is the it's location in the file. So after the 2 byte
502 # header and the fanouttable.
503 rawindex = self.createindex(locations, 2 + len(rawfanouttable))
504
505 self._writeheader(params)
506 self.idxfp.write(rawfanouttable)
507 self.idxfp.write(rawentrieslength)
508 self.idxfp.write(rawindex)
509 self.idxfp.close()
510
511 def createindex(self, nodelocations, indexoffset):
512 raise NotImplementedError()
513
514 def _writeheader(self, indexparams):
515 # Index header
516 # <version: 1 byte>
517 # <large fanout: 1 bit> # 1 means 2^16, 0 means 2^8
518 # <unused: 7 bit> # future use (compression, delta format, etc)
519 config = 0
520 if indexparams.fanoutprefix == LARGEFANOUTPREFIX:
521 config = 0b10000000
522 self.idxfp.write(struct.pack(b'!BB', self.VERSION, config))
523
524
525 class indexparams:
526 __slots__ = (
527 'fanoutprefix',
528 'fanoutstruct',
529 'fanoutcount',
530 'fanoutsize',
531 'indexstart',
532 )
533
534 def __init__(self, prefixsize, version):
535 self.fanoutprefix = prefixsize
536
537 # The struct pack format for fanout table location (i.e. the format that
538 # converts the node prefix into an integer location in the fanout
539 # table).
540 if prefixsize == SMALLFANOUTPREFIX:
541 self.fanoutstruct = b'!B'
542 elif prefixsize == LARGEFANOUTPREFIX:
543 self.fanoutstruct = b'!H'
544 else:
545 raise ValueError(b"invalid fanout prefix size: %s" % prefixsize)
546
547 # The number of fanout table entries
548 self.fanoutcount = 2 ** (prefixsize * 8)
549
550 # The total bytes used by the fanout table
551 self.fanoutsize = self.fanoutcount * 4
552
553 self.indexstart = FANOUTSTART + self.fanoutsize
554 # Skip the index length
555 self.indexstart += 8