Debian Codegraph @

hgext/remotefilelog/fileserverclient.py

raw
1 # fileserverclient.py - client for communicating with the cache process
2 #
3 # Copyright 2013 Facebook, Inc.
4 #
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
7
8 from __future__ import annotations
9
10 import io
11 import os
12 import threading
13 import time
14 import zlib
15
16 from mercurial.i18n import _
17 from mercurial.node import bin, hex
18 from mercurial import (
19 error,
20 pycompat,
21 revlog,
22 sshpeer,
23 util,
24 wireprotov1peer,
25 )
26 from mercurial.utils import (
27 hashutil,
28 procutil,
29 )
30
31 from . import (
32 basestore,
33 constants,
34 contentstore,
35 metadatastore,
36 )
37
38 _sshv1peer = sshpeer.sshv1peer
39
40 # Statistics for debugging
41 fetchcost = 0
42 fetches = 0
43 fetched = 0
44 fetchmisses = 0
45
46 _lfsmod = None
47
48
49 def getcachekey(reponame, file, id):
50 pathhash = hex(hashutil.sha1(file).digest())
51 return os.path.join(reponame, pathhash[:2], pathhash[2:], id)
52
53
54 def getlocalkey(file, id):
55 pathhash = hex(hashutil.sha1(file).digest())
56 return os.path.join(pathhash, id)
57
58
59 def peersetup(ui, peer):
60 class remotefilepeer(peer.__class__):
61 @wireprotov1peer.batchable
62 def x_rfl_getfile(self, file, node):
63 if not self.capable(b'x_rfl_getfile'):
64 raise error.Abort(
65 b'configured remotefile server does not support getfile'
66 )
67
68 def decode(d):
69 code, data = d.split(b'\0', 1)
70 if int(code):
71 raise error.LookupError(file, node, data)
72 return data
73
74 return {b'file': file, b'node': node}, decode
75
76 @wireprotov1peer.batchable
77 def x_rfl_getflogheads(self, path):
78 if not self.capable(b'x_rfl_getflogheads'):
79 raise error.Abort(
80 b'configured remotefile server does not '
81 b'support getflogheads'
82 )
83
84 def decode(d):
85 return d.split(b'\n') if d else []
86
87 return {b'path': path}, decode
88
89 def _updatecallstreamopts(self, command, opts):
90 if command != b'getbundle':
91 return
92 if (
93 constants.NETWORK_CAP_LEGACY_SSH_GETFILES
94 not in self.capabilities()
95 ):
96 return
97 if not hasattr(self, '_localrepo'):
98 return
99 if (
100 constants.SHALLOWREPO_REQUIREMENT
101 not in self._localrepo.requirements
102 ):
103 return
104
105 bundlecaps = opts.get(b'bundlecaps')
106 if bundlecaps:
107 bundlecaps = [bundlecaps]
108 else:
109 bundlecaps = []
110
111 # shallow, includepattern, and excludepattern are a hacky way of
112 # carrying over data from the local repo to this getbundle
113 # command. We need to do it this way because bundle1 getbundle
114 # doesn't provide any other place we can hook in to manipulate
115 # getbundle args before it goes across the wire. Once we get rid
116 # of bundle1, we can use bundle2's _pullbundle2extraprepare to
117 # do this more cleanly.
118 bundlecaps.append(constants.BUNDLE2_CAPABLITY)
119 if self._localrepo.includepattern:
120 patterns = b'\0'.join(self._localrepo.includepattern)
121 includecap = b"includepattern=" + patterns
122 bundlecaps.append(includecap)
123 if self._localrepo.excludepattern:
124 patterns = b'\0'.join(self._localrepo.excludepattern)
125 excludecap = b"excludepattern=" + patterns
126 bundlecaps.append(excludecap)
127 opts[b'bundlecaps'] = b','.join(bundlecaps)
128
129 def _sendrequest(self, command, args, **opts):
130 self._updatecallstreamopts(command, args)
131 return super()._sendrequest(command, args, **opts)
132
133 def _callstream(self, command, **opts):
134 supertype = super()
135 if not hasattr(supertype, '_sendrequest'):
136 self._updatecallstreamopts(command, pycompat.byteskwargs(opts))
137 return super()._callstream(command, **opts)
138
139 peer.__class__ = remotefilepeer
140
141
142 class cacheconnection:
143 """The connection for communicating with the remote cache. Performs
144 gets and sets by communicating with an external process that has the
145 cache-specific implementation.
146 """
147
148 def __init__(self):
149 self.pipeo = self.pipei = self.pipee = None
150 self.subprocess = None
151 self.connected = False
152
153 def connect(self, cachecommand):
154 if self.pipeo:
155 raise error.Abort(_(b"cache connection already open"))
156 self.pipei, self.pipeo, self.pipee, self.subprocess = procutil.popen4(
157 cachecommand
158 )
159 self.connected = True
160
161 def close(self):
162 def tryclose(pipe):
163 try:
164 pipe.close()
165 except Exception:
166 pass
167
168 if self.connected:
169 try:
170 self.pipei.write(b"exit\n")
171 except Exception:
172 pass
173 tryclose(self.pipei)
174 self.pipei = None
175 tryclose(self.pipeo)
176 self.pipeo = None
177 tryclose(self.pipee)
178 self.pipee = None
179 try:
180 # Wait for process to terminate, making sure to avoid deadlock.
181 # See https://docs.python.org/2/library/subprocess.html for
182 # warnings about wait() and deadlocking.
183 self.subprocess.communicate()
184 except Exception:
185 pass
186 self.subprocess = None
187 self.connected = False
188
189 def request(self, request, flush=True):
190 if self.connected:
191 try:
192 self.pipei.write(request)
193 if flush:
194 self.pipei.flush()
195 except OSError:
196 self.close()
197
198 def receiveline(self):
199 if not self.connected:
200 return None
201 try:
202 result = self.pipeo.readline()[:-1]
203 if not result:
204 self.close()
205 except OSError:
206 self.close()
207
208 return result
209
210
211 def _getfilesbatch(
212 remote, receivemissing, progresstick, missed, idmap, batchsize
213 ):
214 # Over http(s), iterbatch is a streamy method and we can start
215 # looking at results early. This means we send one (potentially
216 # large) request, but then we show nice progress as we process
217 # file results, rather than showing chunks of $batchsize in
218 # progress.
219 #
220 # Over ssh, iterbatch isn't streamy because batch() wasn't
221 # explicitly designed as a streaming method. In the future we
222 # should probably introduce a streambatch() method upstream and
223 # use that for this.
224 with remote.commandexecutor() as e:
225 futures = []
226 for m in missed:
227 futures.append(
228 e.callcommand(
229 b'x_rfl_getfile', {b'file': idmap[m], b'node': m[-40:]}
230 )
231 )
232
233 for i, m in enumerate(missed):
234 r = futures[i].result()
235 futures[i] = None # release memory
236 file_ = idmap[m]
237 node = m[-40:]
238 receivemissing(io.BytesIO(b'%d\n%s' % (len(r), r)), file_, node)
239 progresstick()
240
241
242 def _getfiles_optimistic(
243 remote, receivemissing, progresstick, missed, idmap, step
244 ):
245 remote._callstream(b"x_rfl_getfiles")
246 i = 0
247 pipeo = remote._pipeo
248 pipei = remote._pipei
249 while i < len(missed):
250 # issue a batch of requests
251 start = i
252 end = min(len(missed), start + step)
253 i = end
254 for missingid in missed[start:end]:
255 # issue new request
256 versionid = missingid[-40:]
257 file = idmap[missingid]
258 sshrequest = b"%s%s\n" % (versionid, file)
259 pipeo.write(sshrequest)
260 pipeo.flush()
261
262 # receive batch results
263 for missingid in missed[start:end]:
264 versionid = missingid[-40:]
265 file = idmap[missingid]
266 receivemissing(pipei, file, versionid)
267 progresstick()
268
269 # End the command
270 pipeo.write(b'\n')
271 pipeo.flush()
272
273
274 def _getfiles_threaded(
275 remote, receivemissing, progresstick, missed, idmap, step
276 ):
277 remote._callstream(b"x_rfl_getfiles")
278 pipeo = remote._pipeo
279 pipei = remote._pipei
280
281 def writer():
282 for missingid in missed:
283 versionid = missingid[-40:]
284 file = idmap[missingid]
285 sshrequest = b"%s%s\n" % (versionid, file)
286 pipeo.write(sshrequest)
287 pipeo.flush()
288
289 writerthread = threading.Thread(target=writer)
290 writerthread.daemon = True
291 writerthread.start()
292
293 for missingid in missed:
294 versionid = missingid[-40:]
295 file = idmap[missingid]
296 receivemissing(pipei, file, versionid)
297 progresstick()
298
299 writerthread.join()
300 # End the command
301 pipeo.write(b'\n')
302 pipeo.flush()
303
304
305 class fileserverclient:
306 """A client for requesting files from the remote file server."""
307
308 datastore: basestore.basestore
309 historystore: basestore.basestore
310 writedata: basestore.basestore
311 writehistory: basestore.basestore
312
313 def __init__(self, repo):
314 ui = repo.ui
315 self.repo = repo
316 self.ui = ui
317 self.cacheprocess = ui.config(b"remotefilelog", b"cacheprocess")
318 if self.cacheprocess:
319 self.cacheprocess = util.expandpath(self.cacheprocess)
320
321 # This option causes remotefilelog to pass the full file path to the
322 # cacheprocess instead of a hashed key.
323 self.cacheprocesspasspath = ui.configbool(
324 b"remotefilelog", b"cacheprocess.includepath"
325 )
326
327 self.debugoutput = ui.configbool(b"remotefilelog", b"debug")
328
329 self.remotecache = cacheconnection()
330
331 def setstore(self, datastore, historystore, writedata, writehistory):
332 self.datastore = datastore
333 self.historystore = historystore
334 self.writedata = writedata
335 self.writehistory = writehistory
336
337 def _connect(self):
338 return self.repo.connectionpool.get(self.repo.fallbackpath)
339
340 def request(self, fileids):
341 """Takes a list of filename/node pairs and fetches them from the
342 server. Files are stored in the local cache.
343 A list of nodes that the server couldn't find is returned.
344 If the connection fails, an exception is raised.
345 """
346 if not self.remotecache.connected:
347 self.connect()
348 cache = self.remotecache
349 writedata = self.writedata
350
351 repo = self.repo
352 total = len(fileids)
353 request = b"get\n%d\n" % total
354 idmap = {}
355 reponame = repo.name
356 for file, id in fileids:
357 fullid = getcachekey(reponame, file, id)
358 if self.cacheprocesspasspath:
359 request += file + b'\0'
360 request += fullid + b"\n"
361 idmap[fullid] = file
362
363 cache.request(request)
364
365 progress = self.ui.makeprogress(_(b'downloading'), total=total)
366 progress.update(0)
367
368 missed = []
369 while True:
370 missingid = cache.receiveline()
371 if not missingid:
372 missedset = set(missed)
373 for missingid in idmap:
374 if not missingid in missedset:
375 missed.append(missingid)
376 self.ui.warn(
377 _(
378 b"warning: cache connection closed early - "
379 + b"falling back to server\n"
380 )
381 )
382 break
383 if missingid == b"0":
384 break
385 if missingid.startswith(b"_hits_"):
386 # receive progress reports
387 parts = missingid.split(b"_")
388 progress.increment(int(parts[2]))
389 continue
390
391 missed.append(missingid)
392
393 global fetchmisses
394 fetchmisses += len(missed)
395
396 fromcache = total - len(missed)
397 progress.update(fromcache, total=total)
398 self.ui.log(
399 b"remotefilelog",
400 b"remote cache hit rate is %r of %r\n",
401 fromcache,
402 total,
403 hit=fromcache,
404 total=total,
405 )
406
407 oldumask = os.umask(0o002)
408 try:
409 # receive cache misses from master
410 if missed:
411 # When verbose is true, sshpeer prints 'running ssh...'
412 # to stdout, which can interfere with some command
413 # outputs
414 verbose = self.ui.verbose
415 self.ui.verbose = False
416 try:
417 with self._connect() as conn:
418 remote = conn.peer
419 if remote.capable(
420 constants.NETWORK_CAP_LEGACY_SSH_GETFILES
421 ):
422 if not isinstance(remote, _sshv1peer):
423 raise error.Abort(
424 b'remotefilelog requires ssh servers'
425 )
426 step = self.ui.configint(
427 b'remotefilelog', b'getfilesstep'
428 )
429 getfilestype = self.ui.config(
430 b'remotefilelog', b'getfilestype'
431 )
432 if getfilestype == b'threaded':
433 _getfiles = _getfiles_threaded
434 else:
435 _getfiles = _getfiles_optimistic
436 _getfiles(
437 remote,
438 self.receivemissing,
439 progress.increment,
440 missed,
441 idmap,
442 step,
443 )
444 elif remote.capable(b"x_rfl_getfile"):
445 if remote.capable(b'batch'):
446 batchdefault = 100
447 else:
448 batchdefault = 10
449 batchsize = self.ui.configint(
450 b'remotefilelog', b'batchsize', batchdefault
451 )
452 self.ui.debug(
453 b'requesting %d files from '
454 b'remotefilelog server...\n' % len(missed)
455 )
456 _getfilesbatch(
457 remote,
458 self.receivemissing,
459 progress.increment,
460 missed,
461 idmap,
462 batchsize,
463 )
464 else:
465 raise error.Abort(
466 b"configured remotefilelog server"
467 b" does not support remotefilelog"
468 )
469
470 self.ui.log(
471 b"remotefilefetchlog",
472 b"Success\n",
473 fetched_files=progress.pos - fromcache,
474 total_to_fetch=total - fromcache,
475 )
476 except Exception:
477 self.ui.log(
478 b"remotefilefetchlog",
479 b"Fail\n",
480 fetched_files=progress.pos - fromcache,
481 total_to_fetch=total - fromcache,
482 )
483 raise
484 finally:
485 self.ui.verbose = verbose
486 # send to memcache
487 request = b"set\n%d\n%s\n" % (len(missed), b"\n".join(missed))
488 cache.request(request)
489
490 progress.complete()
491
492 # mark ourselves as a user of this cache
493 writedata.markrepo(self.repo.path)
494 finally:
495 os.umask(oldumask)
496
497 def receivemissing(self, pipe, filename, node):
498 line = pipe.readline()[:-1]
499 if not line:
500 raise error.ResponseError(
501 _(b"error downloading file contents:"),
502 _(b"connection closed early"),
503 )
504 size = int(line)
505 data = pipe.read(size)
506 if len(data) != size:
507 raise error.ResponseError(
508 _(b"error downloading file contents:"),
509 _(b"only received %s of %s bytes") % (len(data), size),
510 )
511
512 self.writedata.addremotefilelognode(
513 filename, bin(node), zlib.decompress(data)
514 )
515
516 def connect(self):
517 if self.cacheprocess:
518 cmd = b"%s %s" % (self.cacheprocess, self.writedata._path)
519 self.remotecache.connect(cmd)
520 else:
521 # If no cache process is specified, we fake one that always
522 # returns cache misses. This enables tests to run easily
523 # and may eventually allow us to be a drop in replacement
524 # for the largefiles extension.
525 class simplecache:
526 def __init__(self):
527 self.missingids = []
528 self.connected = True
529
530 def connect(self, cmd): # please pytype
531 pass
532
533 def close(self):
534 pass
535
536 def request(self, value, flush=True):
537 lines = value.split(b"\n")
538 if lines[0] != b"get":
539 return
540 self.missingids = lines[2:-1]
541 self.missingids.append(b'0')
542
543 def receiveline(self):
544 if len(self.missingids) > 0:
545 return self.missingids.pop(0)
546 return None
547
548 self.remotecache = simplecache()
549
550 def close(self):
551 if fetches:
552 msg = (
553 b"%d files fetched over %d fetches - "
554 + b"(%d misses, %0.2f%% hit ratio) over %0.2fs\n"
555 ) % (
556 fetched,
557 fetches,
558 fetchmisses,
559 float(fetched - fetchmisses) / float(fetched) * 100.0,
560 fetchcost,
561 )
562 if self.debugoutput:
563 self.ui.warn(msg)
564 self.ui.log(
565 b"remotefilelog.prefetch",
566 msg.replace(b"%", b"%%"),
567 remotefilelogfetched=fetched,
568 remotefilelogfetches=fetches,
569 remotefilelogfetchmisses=fetchmisses,
570 remotefilelogfetchtime=fetchcost * 1000,
571 )
572
573 if self.remotecache.connected:
574 self.remotecache.close()
575
576 def prefetch(
577 self, fileids, force=False, fetchdata=True, fetchhistory=False
578 ):
579 """downloads the given file versions to the cache"""
580 repo = self.repo
581 idstocheck = []
582 for file, id in fileids:
583 # hack
584 # - we don't use .hgtags
585 # - workingctx produces ids with length 42,
586 # which we skip since they aren't in any cache
587 if (
588 file == b'.hgtags'
589 or len(id) == 42
590 or not repo.shallowmatch(file)
591 ):
592 continue
593
594 idstocheck.append((file, bin(id)))
595
596 datastore = self.datastore
597 historystore = self.historystore
598 if force:
599 datastore = contentstore.unioncontentstore(*repo.shareddatastores)
600 historystore = metadatastore.unionmetadatastore(
601 *repo.sharedhistorystores
602 )
603
604 missingids = set()
605 if fetchdata:
606 missingids.update(datastore.getmissing(idstocheck))
607 if fetchhistory:
608 missingids.update(historystore.getmissing(idstocheck))
609
610 # partition missing nodes into nullid and not-nullid so we can
611 # warn about this filtering potentially shadowing bugs.
612 nullids = len(
613 [None for unused, id in missingids if id == self.repo.nullid]
614 )
615 if nullids:
616 missingids = [
617 (f, id) for f, id in missingids if id != self.repo.nullid
618 ]
619 repo.ui.develwarn(
620 (
621 b'remotefilelog not fetching %d null revs'
622 b' - this is likely hiding bugs' % nullids
623 ),
624 config=b'remotefilelog-ext',
625 )
626 if missingids:
627 global fetches, fetched, fetchcost
628 fetches += 1
629
630 # We want to be able to detect excess individual file downloads, so
631 # let's log that information for debugging.
632 if fetches >= 15 and fetches < 18:
633 if fetches == 15:
634 fetchwarning = self.ui.config(
635 b'remotefilelog', b'fetchwarning'
636 )
637 if fetchwarning:
638 self.ui.warn(fetchwarning + b'\n')
639 self.logstacktrace()
640 missingids = [(file, hex(id)) for file, id in sorted(missingids)]
641 fetched += len(missingids)
642 start = time.time()
643 missingids = self.request(missingids)
644 if missingids:
645 raise error.Abort(
646 _(b"unable to download %d files") % len(missingids)
647 )
648 fetchcost += time.time() - start
649 self._lfsprefetch(fileids)
650
651 def _lfsprefetch(self, fileids):
652 if not _lfsmod or not hasattr(self.repo.svfs, 'lfslocalblobstore'):
653 return
654 if not _lfsmod.wrapper.candownload(self.repo):
655 return
656 pointers = []
657 store = self.repo.svfs.lfslocalblobstore
658 for file, id in fileids:
659 node = bin(id)
660 rlog = self.repo.file(file)
661 if rlog.flags(node) & revlog.REVIDX_EXTSTORED:
662 text = rlog.rawdata(node)
663 p = _lfsmod.pointer.deserialize(text)
664 oid = p.oid()
665 if not store.has(oid):
666 pointers.append(p)
667 if len(pointers) > 0:
668 self.repo.svfs.lfsremoteblobstore.readbatch(pointers, store)
669 assert all(store.has(p.oid()) for p in pointers)
670
671 def logstacktrace(self):
672 import traceback
673
674 self.ui.log(
675 b'remotefilelog',
676 b'excess remotefilelog fetching:\n%s\n',
677 b''.join(pycompat.sysbytes(s) for s in traceback.format_stack()),
678 )