| 1 |
# remotefilelogserver.py - server logic for a remotefilelog server |
| 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 os |
| 11 |
import stat |
| 12 |
import time |
| 13 |
import zlib |
| 14 |
|
| 15 |
from mercurial.i18n import _ |
| 16 |
from mercurial.node import bin, hex |
| 17 |
from mercurial import ( |
| 18 |
changegroup, |
| 19 |
changelog, |
| 20 |
context, |
| 21 |
error, |
| 22 |
extensions, |
| 23 |
match, |
| 24 |
scmutil, |
| 25 |
store, |
| 26 |
streamclone, |
| 27 |
util, |
| 28 |
wireprotoserver, |
| 29 |
wireprototypes, |
| 30 |
wireprotov1server, |
| 31 |
) |
| 32 |
from . import ( |
| 33 |
constants, |
| 34 |
shallowutil, |
| 35 |
) |
| 36 |
|
| 37 |
_sshv1server = wireprotoserver.sshv1protocolhandler |
| 38 |
|
| 39 |
|
| 40 |
def setupserver(ui, repo): |
| 41 |
"""Sets up a normal Mercurial repo so it can serve files to shallow repos.""" |
| 42 |
onetimesetup(ui) |
| 43 |
|
| 44 |
# don't send files to shallow clients during pulls |
| 45 |
def generatefiles( |
| 46 |
orig, self, changedfiles, linknodes, commonrevs, source, *args, **kwargs |
| 47 |
): |
| 48 |
caps = self._bundlecaps or [] |
| 49 |
if constants.BUNDLE2_CAPABLITY in caps: |
| 50 |
# only send files that don't match the specified patterns |
| 51 |
includepattern = None |
| 52 |
excludepattern = None |
| 53 |
for cap in self._bundlecaps or []: |
| 54 |
if cap.startswith(b"includepattern="): |
| 55 |
includepattern = cap[len(b"includepattern=") :].split(b'\0') |
| 56 |
elif cap.startswith(b"excludepattern="): |
| 57 |
excludepattern = cap[len(b"excludepattern=") :].split(b'\0') |
| 58 |
|
| 59 |
m = match.always() |
| 60 |
if includepattern or excludepattern: |
| 61 |
m = match.match( |
| 62 |
repo.root, b'', None, includepattern, excludepattern |
| 63 |
) |
| 64 |
|
| 65 |
changedfiles = [f for f in changedfiles if not m(f)] |
| 66 |
return orig( |
| 67 |
self, changedfiles, linknodes, commonrevs, source, *args, **kwargs |
| 68 |
) |
| 69 |
|
| 70 |
extensions.wrapfunction( |
| 71 |
changegroup.cgpacker, 'generatefiles', generatefiles |
| 72 |
) |
| 73 |
|
| 74 |
|
| 75 |
onetime = False |
| 76 |
|
| 77 |
|
| 78 |
def onetimesetup(ui): |
| 79 |
"""Configures the wireprotocol for both clients and servers.""" |
| 80 |
global onetime |
| 81 |
if onetime: |
| 82 |
return |
| 83 |
onetime = True |
| 84 |
|
| 85 |
# support file content requests |
| 86 |
wireprotov1server.wireprotocommand( |
| 87 |
b'x_rfl_getflogheads', b'path', permission=b'pull' |
| 88 |
)(getflogheads) |
| 89 |
wireprotov1server.wireprotocommand( |
| 90 |
b'x_rfl_getfiles', b'', permission=b'pull' |
| 91 |
)(getfiles) |
| 92 |
wireprotov1server.wireprotocommand( |
| 93 |
b'x_rfl_getfile', b'file node', permission=b'pull' |
| 94 |
)(getfile) |
| 95 |
|
| 96 |
class streamstate: |
| 97 |
match = None |
| 98 |
shallowremote = False |
| 99 |
noflatmf = False |
| 100 |
|
| 101 |
state = streamstate() |
| 102 |
|
| 103 |
def stream_out_shallow(repo, proto, other): |
| 104 |
includepattern = None |
| 105 |
excludepattern = None |
| 106 |
raw = other.get(b'includepattern') |
| 107 |
if raw: |
| 108 |
includepattern = raw.split(b'\0') |
| 109 |
raw = other.get(b'excludepattern') |
| 110 |
if raw: |
| 111 |
excludepattern = raw.split(b'\0') |
| 112 |
|
| 113 |
oldshallow = state.shallowremote |
| 114 |
oldmatch = state.match |
| 115 |
oldnoflatmf = state.noflatmf |
| 116 |
try: |
| 117 |
state.shallowremote = True |
| 118 |
state.match = match.always() |
| 119 |
state.noflatmf = other.get(b'noflatmanifest') == b'True' |
| 120 |
if includepattern or excludepattern: |
| 121 |
state.match = match.match( |
| 122 |
repo.root, b'', None, includepattern, excludepattern |
| 123 |
) |
| 124 |
streamres = wireprotov1server.stream(repo, proto) |
| 125 |
|
| 126 |
# Force the first value to execute, so the file list is computed |
| 127 |
# within the try/finally scope |
| 128 |
first = next(streamres.gen) |
| 129 |
second = next(streamres.gen) |
| 130 |
|
| 131 |
def gen(): |
| 132 |
yield first |
| 133 |
yield second |
| 134 |
yield from streamres.gen |
| 135 |
|
| 136 |
return wireprototypes.streamres(gen()) |
| 137 |
finally: |
| 138 |
state.shallowremote = oldshallow |
| 139 |
state.match = oldmatch |
| 140 |
state.noflatmf = oldnoflatmf |
| 141 |
|
| 142 |
wireprotov1server.commands[b'stream_out_shallow'] = ( |
| 143 |
stream_out_shallow, |
| 144 |
b'*', |
| 145 |
) |
| 146 |
|
| 147 |
# don't clone filelogs to shallow clients |
| 148 |
def _walkstreamfiles( |
| 149 |
orig, repo, matcher=None, phase=False, obsolescence=False |
| 150 |
): |
| 151 |
if state.shallowremote: |
| 152 |
# if we are shallow ourselves, stream our local commits |
| 153 |
if shallowutil.isenabled(repo): |
| 154 |
striplen = len(repo.store.path) + 1 |
| 155 |
readdir = repo.store.rawvfs.readdir |
| 156 |
visit = [os.path.join(repo.store.path, b'data')] |
| 157 |
while visit: |
| 158 |
p = visit.pop() |
| 159 |
for f, kind, st in readdir(p, stat=True): |
| 160 |
fp = p + b'/' + f |
| 161 |
if kind == stat.S_IFREG: |
| 162 |
if not fp.endswith(b'.i') and not fp.endswith( |
| 163 |
b'.d' |
| 164 |
): |
| 165 |
n = util.pconvert(fp[striplen:]) |
| 166 |
d = store.decodedir(n) |
| 167 |
yield store.SimpleStoreEntry( |
| 168 |
entry_path=d, |
| 169 |
is_volatile=False, |
| 170 |
file_size=st.st_size, |
| 171 |
) |
| 172 |
|
| 173 |
if kind == stat.S_IFDIR: |
| 174 |
visit.append(fp) |
| 175 |
|
| 176 |
if scmutil.istreemanifest(repo): |
| 177 |
for entry in repo.store.data_entries(): |
| 178 |
if entry.is_manifestlog: |
| 179 |
yield entry |
| 180 |
|
| 181 |
# Return .d and .i files that do not match the shallow pattern |
| 182 |
match = state.match |
| 183 |
if match and not match.always(): |
| 184 |
for entry in repo.store.data_entries(): |
| 185 |
if not entry.is_revlog: |
| 186 |
continue |
| 187 |
if not state.match(entry.target_id): |
| 188 |
yield entry |
| 189 |
|
| 190 |
for x in repo.store.top_entries(): |
| 191 |
if state.noflatmf and x[1][:11] == b'00manifest.': |
| 192 |
continue |
| 193 |
yield x |
| 194 |
|
| 195 |
elif shallowutil.isenabled(repo): |
| 196 |
# don't allow cloning from a shallow repo to a full repo |
| 197 |
# since it would require fetching every version of every |
| 198 |
# file in order to create the revlogs. |
| 199 |
raise error.Abort( |
| 200 |
_(b"Cannot clone from a shallow repo to a full repo.") |
| 201 |
) |
| 202 |
else: |
| 203 |
for x in orig( |
| 204 |
repo, matcher, phase=phase, obsolescence=obsolescence |
| 205 |
): |
| 206 |
yield x |
| 207 |
|
| 208 |
extensions.wrapfunction(streamclone, '_walkstreamfiles', _walkstreamfiles) |
| 209 |
|
| 210 |
# expose remotefilelog capabilities |
| 211 |
def _capabilities(orig, repo, proto): |
| 212 |
caps = orig(repo, proto) |
| 213 |
if shallowutil.isenabled(repo) or ui.configbool( |
| 214 |
b'remotefilelog', b'server' |
| 215 |
): |
| 216 |
if isinstance(proto, _sshv1server): |
| 217 |
# legacy getfiles method which only works over ssh |
| 218 |
caps.append(constants.NETWORK_CAP_LEGACY_SSH_GETFILES) |
| 219 |
caps.append(b'x_rfl_getflogheads') |
| 220 |
caps.append(b'x_rfl_getfile') |
| 221 |
return caps |
| 222 |
|
| 223 |
extensions.wrapfunction(wireprotov1server, '_capabilities', _capabilities) |
| 224 |
|
| 225 |
def _adjustlinkrev(orig, self, *args, **kwargs): |
| 226 |
# When generating file blobs, taking the real path is too slow on large |
| 227 |
# repos, so force it to just return the linkrev directly. |
| 228 |
repo = self._repo |
| 229 |
if hasattr(repo, 'forcelinkrev') and repo.forcelinkrev: |
| 230 |
return self._filelog.linkrev(self._filelog.rev(self._filenode)) |
| 231 |
return orig(self, *args, **kwargs) |
| 232 |
|
| 233 |
extensions.wrapfunction( |
| 234 |
context.basefilectx, '_adjustlinkrev', _adjustlinkrev |
| 235 |
) |
| 236 |
|
| 237 |
def _iscmd(orig, cmd): |
| 238 |
if cmd == b'x_rfl_getfiles': |
| 239 |
return False |
| 240 |
return orig(cmd) |
| 241 |
|
| 242 |
extensions.wrapfunction(wireprotoserver, 'iscmd', _iscmd) |
| 243 |
|
| 244 |
|
| 245 |
def _loadfileblob(repo, cachepath, path, node): |
| 246 |
filecachepath = os.path.join(cachepath, path, hex(node)) |
| 247 |
if not os.path.exists(filecachepath) or os.path.getsize(filecachepath) == 0: |
| 248 |
filectx = repo.filectx(path, fileid=node) |
| 249 |
if filectx.node() == repo.nullid: |
| 250 |
repo.changelog = changelog.changelog(repo.svfs) |
| 251 |
filectx = repo.filectx(path, fileid=node) |
| 252 |
|
| 253 |
text = createfileblob(filectx) |
| 254 |
# TODO configurable compression engines |
| 255 |
text = zlib.compress(text) |
| 256 |
|
| 257 |
# everything should be user & group read/writable |
| 258 |
oldumask = os.umask(0o002) |
| 259 |
try: |
| 260 |
dirname = os.path.dirname(filecachepath) |
| 261 |
if not os.path.exists(dirname): |
| 262 |
try: |
| 263 |
os.makedirs(dirname) |
| 264 |
except FileExistsError: |
| 265 |
pass |
| 266 |
|
| 267 |
f = None |
| 268 |
try: |
| 269 |
f = util.atomictempfile(filecachepath, b"wb") |
| 270 |
f.write(text) |
| 271 |
except OSError: |
| 272 |
# Don't abort if the user only has permission to read, |
| 273 |
# and not write. |
| 274 |
pass |
| 275 |
finally: |
| 276 |
if f: |
| 277 |
f.close() |
| 278 |
finally: |
| 279 |
os.umask(oldumask) |
| 280 |
else: |
| 281 |
with open(filecachepath, "rb") as f: |
| 282 |
text = f.read() |
| 283 |
return text |
| 284 |
|
| 285 |
|
| 286 |
def getflogheads(repo, proto, path): |
| 287 |
"""A server api for requesting a filelog's heads""" |
| 288 |
flog = repo.file(path) |
| 289 |
heads = flog.heads() |
| 290 |
return b'\n'.join(hex(head) for head in heads if head != repo.nullid) |
| 291 |
|
| 292 |
|
| 293 |
def getfile(repo, proto, file, node): |
| 294 |
"""A server api for requesting a particular version of a file. Can be used |
| 295 |
in batches to request many files at once. The return protocol is: |
| 296 |
<errorcode>\0<data/errormsg> where <errorcode> is 0 for success or |
| 297 |
non-zero for an error. |
| 298 |
|
| 299 |
data is a compressed blob with revlog flag and ancestors information. See |
| 300 |
createfileblob for its content. |
| 301 |
""" |
| 302 |
if shallowutil.isenabled(repo): |
| 303 |
return b'1\0' + _(b'cannot fetch remote files from shallow repo') |
| 304 |
cachepath = repo.ui.config(b"remotefilelog", b"servercachepath") |
| 305 |
if not cachepath: |
| 306 |
cachepath = os.path.join(repo.path, b"remotefilelogcache") |
| 307 |
node = bin(node.strip()) |
| 308 |
if node == repo.nullid: |
| 309 |
return b'0\0' |
| 310 |
return b'0\0' + _loadfileblob(repo, cachepath, file, node) |
| 311 |
|
| 312 |
|
| 313 |
def getfiles(repo, proto): |
| 314 |
"""A server api for requesting particular versions of particular files.""" |
| 315 |
if shallowutil.isenabled(repo): |
| 316 |
raise error.Abort(_(b'cannot fetch remote files from shallow repo')) |
| 317 |
if not isinstance(proto, _sshv1server): |
| 318 |
raise error.Abort(_(b'cannot fetch remote files over non-ssh protocol')) |
| 319 |
|
| 320 |
def streamer(): |
| 321 |
fin = proto._fin |
| 322 |
|
| 323 |
cachepath = repo.ui.config(b"remotefilelog", b"servercachepath") |
| 324 |
if not cachepath: |
| 325 |
cachepath = os.path.join(repo.path, b"remotefilelogcache") |
| 326 |
|
| 327 |
while True: |
| 328 |
request = fin.readline()[:-1] |
| 329 |
if not request: |
| 330 |
break |
| 331 |
|
| 332 |
node = bin(request[:40]) |
| 333 |
if node == repo.nullid: |
| 334 |
yield b'0\n' |
| 335 |
continue |
| 336 |
|
| 337 |
path = request[40:] |
| 338 |
|
| 339 |
text = _loadfileblob(repo, cachepath, path, node) |
| 340 |
|
| 341 |
yield b'%d\n%s' % (len(text), text) |
| 342 |
|
| 343 |
# it would be better to only flush after processing a whole batch |
| 344 |
# but currently we don't know if there are more requests coming |
| 345 |
proto._fout.flush() |
| 346 |
|
| 347 |
return wireprototypes.streamres(streamer()) |
| 348 |
|
| 349 |
|
| 350 |
def createfileblob(filectx): |
| 351 |
""" |
| 352 |
format: |
| 353 |
v0: |
| 354 |
str(len(rawtext)) + '\0' + rawtext + ancestortext |
| 355 |
v1: |
| 356 |
'v1' + '\n' + metalist + '\0' + rawtext + ancestortext |
| 357 |
metalist := metalist + '\n' + meta | meta |
| 358 |
meta := sizemeta | flagmeta |
| 359 |
sizemeta := METAKEYSIZE + str(len(rawtext)) |
| 360 |
flagmeta := METAKEYFLAG + str(flag) |
| 361 |
|
| 362 |
note: sizemeta must exist. METAKEYFLAG and METAKEYSIZE must have a |
| 363 |
length of 1. |
| 364 |
""" |
| 365 |
flog = filectx.filelog() |
| 366 |
frev = filectx.filerev() |
| 367 |
revlogflags = flog._revlog.flags(frev) |
| 368 |
if revlogflags == 0: |
| 369 |
# normal files |
| 370 |
text = filectx.data() |
| 371 |
else: |
| 372 |
# lfs, read raw revision data |
| 373 |
text = flog.rawdata(frev) |
| 374 |
|
| 375 |
repo = filectx._repo |
| 376 |
|
| 377 |
ancestors = [filectx] |
| 378 |
|
| 379 |
try: |
| 380 |
repo.forcelinkrev = True |
| 381 |
ancestors.extend([f for f in filectx.ancestors()]) |
| 382 |
|
| 383 |
ancestortext = b"" |
| 384 |
for ancestorctx in ancestors: |
| 385 |
parents = ancestorctx.parents() |
| 386 |
p1 = repo.nullid |
| 387 |
p2 = repo.nullid |
| 388 |
if len(parents) > 0: |
| 389 |
p1 = parents[0].filenode() |
| 390 |
if len(parents) > 1: |
| 391 |
p2 = parents[1].filenode() |
| 392 |
|
| 393 |
copyname = b"" |
| 394 |
rename = ancestorctx.renamed() |
| 395 |
if rename: |
| 396 |
copyname = rename[0] |
| 397 |
linknode = ancestorctx.node() |
| 398 |
ancestortext += b"%s%s%s%s%s\0" % ( |
| 399 |
ancestorctx.filenode(), |
| 400 |
p1, |
| 401 |
p2, |
| 402 |
linknode, |
| 403 |
copyname, |
| 404 |
) |
| 405 |
finally: |
| 406 |
repo.forcelinkrev = False |
| 407 |
|
| 408 |
header = shallowutil.buildfileblobheader(len(text), revlogflags) |
| 409 |
|
| 410 |
return b"%s\0%s%s" % (header, text, ancestortext) |
| 411 |
|
| 412 |
|
| 413 |
def gcserver(ui, repo): |
| 414 |
if not repo.ui.configbool(b"remotefilelog", b"server"): |
| 415 |
return |
| 416 |
|
| 417 |
neededfiles = set() |
| 418 |
heads = repo.revs(b"heads(tip~25000:) - null") |
| 419 |
|
| 420 |
cachepath = repo.vfs.join(b"remotefilelogcache") |
| 421 |
for head in heads: |
| 422 |
mf = repo[head].manifest() |
| 423 |
for filename, filenode in mf.items(): |
| 424 |
filecachepath = os.path.join(cachepath, filename, hex(filenode)) |
| 425 |
neededfiles.add(filecachepath) |
| 426 |
|
| 427 |
# delete unneeded older files |
| 428 |
days = repo.ui.configint(b"remotefilelog", b"serverexpiration") |
| 429 |
expiration = time.time() - (days * 24 * 60 * 60) |
| 430 |
|
| 431 |
progress = ui.makeprogress(_(b"removing old server cache"), unit=b"files") |
| 432 |
progress.update(0) |
| 433 |
for root, dirs, files in os.walk(cachepath): |
| 434 |
for file in files: |
| 435 |
filepath = os.path.join(root, file) |
| 436 |
progress.increment() |
| 437 |
if filepath in neededfiles: |
| 438 |
continue |
| 439 |
|
| 440 |
stat = os.stat(filepath) |
| 441 |
if stat.st_mtime < expiration: |
| 442 |
os.remove(filepath) |
| 443 |
|
| 444 |
progress.complete() |