Debian Codegraph @

hgext/remotefilelog/basestore.py

raw
1 from __future__ import annotations
2
3 import os
4 import shutil
5 import stat
6 import time
7
8 from mercurial.i18n import _
9 from mercurial.node import bin, hex
10 from mercurial import (
11 error,
12 pycompat,
13 util,
14 )
15 from mercurial.utils import hashutil
16 from . import (
17 constants,
18 shallowutil,
19 )
20
21
22 class basestore:
23 def __init__(self, repo, path, reponame, shared=False):
24 """Creates a remotefilelog store object for the given repo name.
25
26 `path` - The file path where this store keeps its data
27 `reponame` - The name of the repo. This is used to partition data from
28 many repos.
29 `shared` - True if this store is a shared cache of data from the central
30 server, for many repos on this machine. False means this store is for
31 the local data for one repo.
32 """
33 self.repo = repo
34 self.ui = repo.ui
35 self._path = path
36 self._reponame = reponame
37 self._shared = shared
38 self._uid = os.getuid() if not pycompat.iswindows else None
39
40 self._validatecachelog = self.ui.config(
41 b"remotefilelog", b"validatecachelog"
42 )
43 self._validatecache = self.ui.config(
44 b"remotefilelog", b"validatecache", b'on'
45 )
46 if self._validatecache not in (b'on', b'strict', b'off'):
47 self._validatecache = b'on'
48 if self._validatecache == b'off':
49 self._validatecache = False
50
51 if shared:
52 shallowutil.mkstickygroupdir(self.ui, path)
53
54 def getmissing(self, keys):
55 missing = []
56 for name, node in keys:
57 filepath = self._getfilepath(name, node)
58 exists = os.path.exists(filepath)
59 if (
60 exists
61 and self._validatecache == b'strict'
62 and not self._validatekey(filepath, b'contains')
63 ):
64 exists = False
65 if not exists:
66 missing.append((name, node))
67
68 return missing
69
70 # BELOW THIS ARE IMPLEMENTATIONS OF REPACK SOURCE
71
72 def markledger(self, ledger, options=None):
73 if options and options.get(constants.OPTION_PACKSONLY):
74 return
75 if self._shared:
76 for filename, nodes in self._getfiles():
77 for node in nodes:
78 ledger.markdataentry(self, filename, node)
79 ledger.markhistoryentry(self, filename, node)
80
81 def cleanup(self, ledger):
82 ui = self.ui
83 entries = ledger.sources.get(self, [])
84 count = 0
85 progress = ui.makeprogress(
86 _(b"cleaning up"), unit=b"files", total=len(entries)
87 )
88 for entry in entries:
89 if entry.gced or (entry.datarepacked and entry.historyrepacked):
90 progress.update(count)
91 path = self._getfilepath(entry.filename, entry.node)
92 util.tryunlink(path)
93 count += 1
94 progress.complete()
95
96 # Clean up the repo cache directory.
97 self._cleanupdirectory(self._getrepocachepath())
98
99 # BELOW THIS ARE NON-STANDARD APIS
100
101 def _cleanupdirectory(self, rootdir):
102 """Removes the empty directories and unnecessary files within the root
103 directory recursively. Note that this method does not remove the root
104 directory itself."""
105
106 oldfiles = set()
107 otherfiles = set()
108 # osutil.listdir returns stat information which saves some rmdir/listdir
109 # syscalls.
110 for name, mode in util.osutil.listdir(rootdir):
111 if stat.S_ISDIR(mode):
112 dirpath = os.path.join(rootdir, name)
113 self._cleanupdirectory(dirpath)
114
115 # Now that the directory specified by dirpath is potentially
116 # empty, try and remove it.
117 try:
118 os.rmdir(dirpath)
119 except OSError:
120 pass
121
122 elif stat.S_ISREG(mode):
123 if name.endswith(b'_old'):
124 oldfiles.add(name[:-4])
125 else:
126 otherfiles.add(name)
127
128 # Remove the files which end with suffix '_old' and have no
129 # corresponding file without the suffix '_old'. See addremotefilelognode
130 # method for the generation/purpose of files with '_old' suffix.
131 for filename in oldfiles - otherfiles:
132 filepath = os.path.join(rootdir, filename + b'_old')
133 util.tryunlink(filepath)
134
135 def _getfiles(self):
136 """Return a list of (filename, [node,...]) for all the revisions that
137 exist in the store.
138
139 This is useful for obtaining a list of all the contents of the store
140 when performing a repack to another store, since the store API requires
141 name+node keys and not namehash+node keys.
142 """
143 existing = {}
144 for filenamehash, node in self._listkeys():
145 existing.setdefault(filenamehash, []).append(node)
146
147 filenamemap = self._resolvefilenames(existing.keys())
148
149 for filename, sha in filenamemap.items():
150 yield (filename, existing[sha])
151
152 def _resolvefilenames(self, hashes):
153 """Given a list of filename hashes that are present in the
154 remotefilelog store, return a mapping from filename->hash.
155
156 This is useful when converting remotefilelog blobs into other storage
157 formats.
158 """
159 if not hashes:
160 return {}
161
162 filenames = {}
163 missingfilename = set(hashes)
164
165 # Start with a full manifest, since it'll cover the majority of files
166 for filename in self.repo[b'tip'].manifest():
167 sha = hashutil.sha1(filename).digest()
168 if sha in missingfilename:
169 filenames[filename] = sha
170 missingfilename.discard(sha)
171
172 # Scan the changelog until we've found every file name
173 cl = self.repo.unfiltered().changelog
174 for rev in range(len(cl) - 1, -1, -1):
175 if not missingfilename:
176 break
177 files = cl.readfiles(cl.node(rev))
178 for filename in files:
179 sha = hashutil.sha1(filename).digest()
180 if sha in missingfilename:
181 filenames[filename] = sha
182 missingfilename.discard(sha)
183
184 return filenames
185
186 def _getrepocachepath(self):
187 return (
188 os.path.join(self._path, self._reponame)
189 if self._shared
190 else self._path
191 )
192
193 def _listkeys(self):
194 """List all the remotefilelog keys that exist in the store.
195
196 Returns a iterator of (filename hash, filecontent hash) tuples.
197 """
198
199 for root, dirs, files in os.walk(self._getrepocachepath()):
200 for filename in files:
201 if len(filename) != 40:
202 continue
203 node = filename
204 if self._shared:
205 # .../1a/85ffda..be21
206 filenamehash = root[-41:-39] + root[-38:]
207 else:
208 filenamehash = root[-40:]
209 yield (bin(filenamehash), bin(node))
210
211 def _getfilepath(self, name, node):
212 node = hex(node)
213 if self._shared:
214 key = shallowutil.getcachekey(self._reponame, name, node)
215 else:
216 key = shallowutil.getlocalkey(name, node)
217
218 return os.path.join(self._path, key)
219
220 def _getdata(self, name, node):
221 filepath = self._getfilepath(name, node)
222 try:
223 data = shallowutil.readfile(filepath)
224 if self._validatecache and not self._validatedata(data, filepath):
225 if self._validatecachelog:
226 with open(self._validatecachelog, 'ab+') as f:
227 f.write(b"corrupt %s during read\n" % filepath)
228 os.rename(filepath, filepath + b".corrupt")
229 raise KeyError(b"corrupt local cache file %s" % filepath)
230 except OSError:
231 raise KeyError(
232 b"no file found at %s for %s:%s" % (filepath, name, hex(node))
233 )
234
235 return data
236
237 def addremotefilelognode(self, name, node, data):
238 filepath = self._getfilepath(name, node)
239
240 oldumask = os.umask(0o002)
241 try:
242 # if this node already exists, save the old version for
243 # recovery/debugging purposes.
244 if os.path.exists(filepath):
245 newfilename = filepath + b'_old'
246 # newfilename can be read-only and shutil.copy will fail.
247 # Delete newfilename to avoid it
248 if os.path.exists(newfilename):
249 shallowutil.unlinkfile(newfilename)
250 shutil.copy(filepath, newfilename)
251
252 shallowutil.mkstickygroupdir(self.ui, os.path.dirname(filepath))
253 shallowutil.writefile(filepath, data, readonly=True)
254
255 if self._validatecache:
256 if not self._validatekey(filepath, b'write'):
257 raise error.Abort(
258 _(b"local cache write was corrupted %s") % filepath
259 )
260 finally:
261 os.umask(oldumask)
262
263 def markrepo(self, path):
264 """Call this to add the given repo path to the store's list of
265 repositories that are using it. This is useful later when doing garbage
266 collection, since it allows us to insecpt the repos to see what nodes
267 they want to be kept alive in the store.
268 """
269 repospath = os.path.join(self._path, b"repos")
270 with open(repospath, 'ab') as reposfile:
271 reposfile.write(os.path.dirname(path) + b"\n")
272
273 repospathstat = os.stat(repospath)
274 if repospathstat.st_uid == self._uid:
275 os.chmod(repospath, 0o0664)
276
277 def _validatekey(self, path, action):
278 with open(path, 'rb') as f:
279 data = f.read()
280
281 if self._validatedata(data, path):
282 return True
283
284 if self._validatecachelog:
285 with open(self._validatecachelog, 'ab+') as f:
286 f.write(b"corrupt %s during %s\n" % (path, action))
287
288 os.rename(path, path + b".corrupt")
289 return False
290
291 def _validatedata(self, data, path):
292 try:
293 if len(data) > 0:
294 # see remotefilelogserver.createfileblob for the format
295 offset, size, flags = shallowutil.parsesizeflags(data)
296 if len(data) <= size:
297 # it is truncated
298 return False
299
300 # extract the node from the metadata
301 offset += size
302 datanode = data[offset : offset + 20]
303
304 # and compare against the path
305 if os.path.basename(path) == hex(datanode):
306 # Content matches the intended path
307 return True
308 return False
309 except (ValueError, shallowutil.BadRemotefilelogHeader):
310 pass
311
312 return False
313
314 def gc(self, keepkeys):
315 ui = self.ui
316 cachepath = self._path
317
318 # prune cache
319 queue = pycompat.queue.PriorityQueue()
320 originalsize = 0
321 size = 0
322 count = 0
323 removed = 0
324
325 # keep files newer than a day even if they aren't needed
326 limit = time.time() - (60 * 60 * 24)
327
328 progress = ui.makeprogress(
329 _(b"removing unnecessary files"), unit=b"files"
330 )
331 progress.update(0)
332 for root, dirs, files in os.walk(cachepath):
333 for file in files:
334 if file == b'repos':
335 continue
336
337 # Don't delete pack files
338 if b'/packs/' in root:
339 continue
340
341 progress.update(count)
342 path = os.path.join(root, file)
343 key = os.path.relpath(path, cachepath)
344 count += 1
345 try:
346 pathstat = os.stat(path)
347 except FileNotFoundError:
348 msg = _(
349 b"warning: file %s was removed by another process\n"
350 )
351 ui.warn(msg % path)
352 continue
353
354 originalsize += pathstat.st_size
355
356 if key in keepkeys or pathstat.st_atime > limit:
357 queue.put((pathstat.st_atime, path, pathstat))
358 size += pathstat.st_size
359 else:
360 try:
361 shallowutil.unlinkfile(path)
362 except FileNotFoundError:
363 msg = _(
364 b"warning: file %s was removed by another "
365 b"process\n"
366 )
367 ui.warn(msg % path)
368 continue
369 removed += 1
370 progress.complete()
371
372 # remove oldest files until under limit
373 limit = ui.configbytes(b"remotefilelog", b"cachelimit")
374 if size > limit:
375 excess = size - limit
376 progress = ui.makeprogress(
377 _(b"enforcing cache limit"), unit=b"bytes", total=excess
378 )
379 removedexcess = 0
380 while queue and size > limit and size > 0:
381 progress.update(removedexcess)
382 atime, oldpath, oldpathstat = queue.get()
383 try:
384 shallowutil.unlinkfile(oldpath)
385 except FileNotFoundError:
386 msg = _(
387 b"warning: file %s was removed by another process\n"
388 )
389 ui.warn(msg % oldpath)
390 size -= oldpathstat.st_size
391 removed += 1
392 removedexcess += oldpathstat.st_size
393 progress.complete()
394
395 ui.status(
396 _(b"finished: removed %d of %d files (%0.2f GB to %0.2f GB)\n")
397 % (
398 removed,
399 count,
400 float(originalsize) / 1024.0 / 1024.0 / 1024.0,
401 float(size) / 1024.0 / 1024.0 / 1024.0,
402 )
403 )
404
405
406 class baseunionstore:
407 def __init__(self, *stores, **kwargs):
408 # If one of the functions that iterates all of the stores is about to
409 # throw a KeyError, try this many times with a full refresh between
410 # attempts. A repack operation may have moved data from one store to
411 # another while we were running.
412 self.numattempts = kwargs.get('numretries', 0) + 1
413 # If not-None, call this function on every retry and if the attempts are
414 # exhausted.
415 self.retrylog = kwargs.get('retrylog', None)
416 self.stores = stores
417
418 def markforrefresh(self):
419 for store in self.stores:
420 if hasattr(store, 'markforrefresh'):
421 store.markforrefresh()
422
423 @staticmethod
424 def retriable(fn):
425 def noop(*args):
426 pass
427
428 def wrapped(self, *args, **kwargs):
429 retrylog = self.retrylog or noop
430 funcname = fn.__name__
431 i = 0
432 while i < self.numattempts:
433 if i > 0:
434 retrylog(
435 b're-attempting (n=%d) %s\n'
436 % (i, pycompat.sysbytes(funcname))
437 )
438 self.markforrefresh()
439 i += 1
440 try:
441 return fn(self, *args, **kwargs)
442 except KeyError:
443 if i == self.numattempts:
444 # retries exhausted
445 retrylog(
446 b'retries exhausted in %s, raising KeyError\n'
447 % pycompat.sysbytes(funcname)
448 )
449 raise
450
451 return wrapped