##// END OF EJS Templates
streamclone: include obsstore file into stream bundle if client can read it
av6 -
r40434:0ac794e0 default
parent child Browse files
Show More
@@ -1,2315 +1,2322 b''
1 1 # bundle2.py - generic container format to transmit arbitrary data.
2 2 #
3 3 # Copyright 2013 Facebook, Inc.
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7 """Handling of the new bundle2 format
8 8
9 9 The goal of bundle2 is to act as an atomically packet to transmit a set of
10 10 payloads in an application agnostic way. It consist in a sequence of "parts"
11 11 that will be handed to and processed by the application layer.
12 12
13 13
14 14 General format architecture
15 15 ===========================
16 16
17 17 The format is architectured as follow
18 18
19 19 - magic string
20 20 - stream level parameters
21 21 - payload parts (any number)
22 22 - end of stream marker.
23 23
24 24 the Binary format
25 25 ============================
26 26
27 27 All numbers are unsigned and big-endian.
28 28
29 29 stream level parameters
30 30 ------------------------
31 31
32 32 Binary format is as follow
33 33
34 34 :params size: int32
35 35
36 36 The total number of Bytes used by the parameters
37 37
38 38 :params value: arbitrary number of Bytes
39 39
40 40 A blob of `params size` containing the serialized version of all stream level
41 41 parameters.
42 42
43 43 The blob contains a space separated list of parameters. Parameters with value
44 44 are stored in the form `<name>=<value>`. Both name and value are urlquoted.
45 45
46 46 Empty name are obviously forbidden.
47 47
48 48 Name MUST start with a letter. If this first letter is lower case, the
49 49 parameter is advisory and can be safely ignored. However when the first
50 50 letter is capital, the parameter is mandatory and the bundling process MUST
51 51 stop if he is not able to proceed it.
52 52
53 53 Stream parameters use a simple textual format for two main reasons:
54 54
55 55 - Stream level parameters should remain simple and we want to discourage any
56 56 crazy usage.
57 57 - Textual data allow easy human inspection of a bundle2 header in case of
58 58 troubles.
59 59
60 60 Any Applicative level options MUST go into a bundle2 part instead.
61 61
62 62 Payload part
63 63 ------------------------
64 64
65 65 Binary format is as follow
66 66
67 67 :header size: int32
68 68
69 69 The total number of Bytes used by the part header. When the header is empty
70 70 (size = 0) this is interpreted as the end of stream marker.
71 71
72 72 :header:
73 73
74 74 The header defines how to interpret the part. It contains two piece of
75 75 data: the part type, and the part parameters.
76 76
77 77 The part type is used to route an application level handler, that can
78 78 interpret payload.
79 79
80 80 Part parameters are passed to the application level handler. They are
81 81 meant to convey information that will help the application level object to
82 82 interpret the part payload.
83 83
84 84 The binary format of the header is has follow
85 85
86 86 :typesize: (one byte)
87 87
88 88 :parttype: alphanumerical part name (restricted to [a-zA-Z0-9_:-]*)
89 89
90 90 :partid: A 32bits integer (unique in the bundle) that can be used to refer
91 91 to this part.
92 92
93 93 :parameters:
94 94
95 95 Part's parameter may have arbitrary content, the binary structure is::
96 96
97 97 <mandatory-count><advisory-count><param-sizes><param-data>
98 98
99 99 :mandatory-count: 1 byte, number of mandatory parameters
100 100
101 101 :advisory-count: 1 byte, number of advisory parameters
102 102
103 103 :param-sizes:
104 104
105 105 N couple of bytes, where N is the total number of parameters. Each
106 106 couple contains (<size-of-key>, <size-of-value) for one parameter.
107 107
108 108 :param-data:
109 109
110 110 A blob of bytes from which each parameter key and value can be
111 111 retrieved using the list of size couples stored in the previous
112 112 field.
113 113
114 114 Mandatory parameters comes first, then the advisory ones.
115 115
116 116 Each parameter's key MUST be unique within the part.
117 117
118 118 :payload:
119 119
120 120 payload is a series of `<chunksize><chunkdata>`.
121 121
122 122 `chunksize` is an int32, `chunkdata` are plain bytes (as much as
123 123 `chunksize` says)` The payload part is concluded by a zero size chunk.
124 124
125 125 The current implementation always produces either zero or one chunk.
126 126 This is an implementation limitation that will ultimately be lifted.
127 127
128 128 `chunksize` can be negative to trigger special case processing. No such
129 129 processing is in place yet.
130 130
131 131 Bundle processing
132 132 ============================
133 133
134 134 Each part is processed in order using a "part handler". Handler are registered
135 135 for a certain part type.
136 136
137 137 The matching of a part to its handler is case insensitive. The case of the
138 138 part type is used to know if a part is mandatory or advisory. If the Part type
139 139 contains any uppercase char it is considered mandatory. When no handler is
140 140 known for a Mandatory part, the process is aborted and an exception is raised.
141 141 If the part is advisory and no handler is known, the part is ignored. When the
142 142 process is aborted, the full bundle is still read from the stream to keep the
143 143 channel usable. But none of the part read from an abort are processed. In the
144 144 future, dropping the stream may become an option for channel we do not care to
145 145 preserve.
146 146 """
147 147
148 148 from __future__ import absolute_import, division
149 149
150 150 import collections
151 151 import errno
152 152 import os
153 153 import re
154 154 import string
155 155 import struct
156 156 import sys
157 157
158 158 from .i18n import _
159 159 from . import (
160 160 bookmarks,
161 161 changegroup,
162 162 encoding,
163 163 error,
164 164 node as nodemod,
165 165 obsolete,
166 166 phases,
167 167 pushkey,
168 168 pycompat,
169 169 streamclone,
170 170 tags,
171 171 url,
172 172 util,
173 173 )
174 174 from .utils import (
175 175 stringutil,
176 176 )
177 177
178 178 urlerr = util.urlerr
179 179 urlreq = util.urlreq
180 180
181 181 _pack = struct.pack
182 182 _unpack = struct.unpack
183 183
184 184 _fstreamparamsize = '>i'
185 185 _fpartheadersize = '>i'
186 186 _fparttypesize = '>B'
187 187 _fpartid = '>I'
188 188 _fpayloadsize = '>i'
189 189 _fpartparamcount = '>BB'
190 190
191 191 preferedchunksize = 32768
192 192
193 193 _parttypeforbidden = re.compile('[^a-zA-Z0-9_:-]')
194 194
195 195 def outdebug(ui, message):
196 196 """debug regarding output stream (bundling)"""
197 197 if ui.configbool('devel', 'bundle2.debug'):
198 198 ui.debug('bundle2-output: %s\n' % message)
199 199
200 200 def indebug(ui, message):
201 201 """debug on input stream (unbundling)"""
202 202 if ui.configbool('devel', 'bundle2.debug'):
203 203 ui.debug('bundle2-input: %s\n' % message)
204 204
205 205 def validateparttype(parttype):
206 206 """raise ValueError if a parttype contains invalid character"""
207 207 if _parttypeforbidden.search(parttype):
208 208 raise ValueError(parttype)
209 209
210 210 def _makefpartparamsizes(nbparams):
211 211 """return a struct format to read part parameter sizes
212 212
213 213 The number parameters is variable so we need to build that format
214 214 dynamically.
215 215 """
216 216 return '>'+('BB'*nbparams)
217 217
218 218 parthandlermapping = {}
219 219
220 220 def parthandler(parttype, params=()):
221 221 """decorator that register a function as a bundle2 part handler
222 222
223 223 eg::
224 224
225 225 @parthandler('myparttype', ('mandatory', 'param', 'handled'))
226 226 def myparttypehandler(...):
227 227 '''process a part of type "my part".'''
228 228 ...
229 229 """
230 230 validateparttype(parttype)
231 231 def _decorator(func):
232 232 lparttype = parttype.lower() # enforce lower case matching.
233 233 assert lparttype not in parthandlermapping
234 234 parthandlermapping[lparttype] = func
235 235 func.params = frozenset(params)
236 236 return func
237 237 return _decorator
238 238
239 239 class unbundlerecords(object):
240 240 """keep record of what happens during and unbundle
241 241
242 242 New records are added using `records.add('cat', obj)`. Where 'cat' is a
243 243 category of record and obj is an arbitrary object.
244 244
245 245 `records['cat']` will return all entries of this category 'cat'.
246 246
247 247 Iterating on the object itself will yield `('category', obj)` tuples
248 248 for all entries.
249 249
250 250 All iterations happens in chronological order.
251 251 """
252 252
253 253 def __init__(self):
254 254 self._categories = {}
255 255 self._sequences = []
256 256 self._replies = {}
257 257
258 258 def add(self, category, entry, inreplyto=None):
259 259 """add a new record of a given category.
260 260
261 261 The entry can then be retrieved in the list returned by
262 262 self['category']."""
263 263 self._categories.setdefault(category, []).append(entry)
264 264 self._sequences.append((category, entry))
265 265 if inreplyto is not None:
266 266 self.getreplies(inreplyto).add(category, entry)
267 267
268 268 def getreplies(self, partid):
269 269 """get the records that are replies to a specific part"""
270 270 return self._replies.setdefault(partid, unbundlerecords())
271 271
272 272 def __getitem__(self, cat):
273 273 return tuple(self._categories.get(cat, ()))
274 274
275 275 def __iter__(self):
276 276 return iter(self._sequences)
277 277
278 278 def __len__(self):
279 279 return len(self._sequences)
280 280
281 281 def __nonzero__(self):
282 282 return bool(self._sequences)
283 283
284 284 __bool__ = __nonzero__
285 285
286 286 class bundleoperation(object):
287 287 """an object that represents a single bundling process
288 288
289 289 Its purpose is to carry unbundle-related objects and states.
290 290
291 291 A new object should be created at the beginning of each bundle processing.
292 292 The object is to be returned by the processing function.
293 293
294 294 The object has very little content now it will ultimately contain:
295 295 * an access to the repo the bundle is applied to,
296 296 * a ui object,
297 297 * a way to retrieve a transaction to add changes to the repo,
298 298 * a way to record the result of processing each part,
299 299 * a way to construct a bundle response when applicable.
300 300 """
301 301
302 302 def __init__(self, repo, transactiongetter, captureoutput=True, source=''):
303 303 self.repo = repo
304 304 self.ui = repo.ui
305 305 self.records = unbundlerecords()
306 306 self.reply = None
307 307 self.captureoutput = captureoutput
308 308 self.hookargs = {}
309 309 self._gettransaction = transactiongetter
310 310 # carries value that can modify part behavior
311 311 self.modes = {}
312 312 self.source = source
313 313
314 314 def gettransaction(self):
315 315 transaction = self._gettransaction()
316 316
317 317 if self.hookargs:
318 318 # the ones added to the transaction supercede those added
319 319 # to the operation.
320 320 self.hookargs.update(transaction.hookargs)
321 321 transaction.hookargs = self.hookargs
322 322
323 323 # mark the hookargs as flushed. further attempts to add to
324 324 # hookargs will result in an abort.
325 325 self.hookargs = None
326 326
327 327 return transaction
328 328
329 329 def addhookargs(self, hookargs):
330 330 if self.hookargs is None:
331 331 raise error.ProgrammingError('attempted to add hookargs to '
332 332 'operation after transaction started')
333 333 self.hookargs.update(hookargs)
334 334
335 335 class TransactionUnavailable(RuntimeError):
336 336 pass
337 337
338 338 def _notransaction():
339 339 """default method to get a transaction while processing a bundle
340 340
341 341 Raise an exception to highlight the fact that no transaction was expected
342 342 to be created"""
343 343 raise TransactionUnavailable()
344 344
345 345 def applybundle(repo, unbundler, tr, source, url=None, **kwargs):
346 346 # transform me into unbundler.apply() as soon as the freeze is lifted
347 347 if isinstance(unbundler, unbundle20):
348 348 tr.hookargs['bundle2'] = '1'
349 349 if source is not None and 'source' not in tr.hookargs:
350 350 tr.hookargs['source'] = source
351 351 if url is not None and 'url' not in tr.hookargs:
352 352 tr.hookargs['url'] = url
353 353 return processbundle(repo, unbundler, lambda: tr, source=source)
354 354 else:
355 355 # the transactiongetter won't be used, but we might as well set it
356 356 op = bundleoperation(repo, lambda: tr, source=source)
357 357 _processchangegroup(op, unbundler, tr, source, url, **kwargs)
358 358 return op
359 359
360 360 class partiterator(object):
361 361 def __init__(self, repo, op, unbundler):
362 362 self.repo = repo
363 363 self.op = op
364 364 self.unbundler = unbundler
365 365 self.iterator = None
366 366 self.count = 0
367 367 self.current = None
368 368
369 369 def __enter__(self):
370 370 def func():
371 371 itr = enumerate(self.unbundler.iterparts())
372 372 for count, p in itr:
373 373 self.count = count
374 374 self.current = p
375 375 yield p
376 376 p.consume()
377 377 self.current = None
378 378 self.iterator = func()
379 379 return self.iterator
380 380
381 381 def __exit__(self, type, exc, tb):
382 382 if not self.iterator:
383 383 return
384 384
385 385 # Only gracefully abort in a normal exception situation. User aborts
386 386 # like Ctrl+C throw a KeyboardInterrupt which is not a base Exception,
387 387 # and should not gracefully cleanup.
388 388 if isinstance(exc, Exception):
389 389 # Any exceptions seeking to the end of the bundle at this point are
390 390 # almost certainly related to the underlying stream being bad.
391 391 # And, chances are that the exception we're handling is related to
392 392 # getting in that bad state. So, we swallow the seeking error and
393 393 # re-raise the original error.
394 394 seekerror = False
395 395 try:
396 396 if self.current:
397 397 # consume the part content to not corrupt the stream.
398 398 self.current.consume()
399 399
400 400 for part in self.iterator:
401 401 # consume the bundle content
402 402 part.consume()
403 403 except Exception:
404 404 seekerror = True
405 405
406 406 # Small hack to let caller code distinguish exceptions from bundle2
407 407 # processing from processing the old format. This is mostly needed
408 408 # to handle different return codes to unbundle according to the type
409 409 # of bundle. We should probably clean up or drop this return code
410 410 # craziness in a future version.
411 411 exc.duringunbundle2 = True
412 412 salvaged = []
413 413 replycaps = None
414 414 if self.op.reply is not None:
415 415 salvaged = self.op.reply.salvageoutput()
416 416 replycaps = self.op.reply.capabilities
417 417 exc._replycaps = replycaps
418 418 exc._bundle2salvagedoutput = salvaged
419 419
420 420 # Re-raising from a variable loses the original stack. So only use
421 421 # that form if we need to.
422 422 if seekerror:
423 423 raise exc
424 424
425 425 self.repo.ui.debug('bundle2-input-bundle: %i parts total\n' %
426 426 self.count)
427 427
428 428 def processbundle(repo, unbundler, transactiongetter=None, op=None, source=''):
429 429 """This function process a bundle, apply effect to/from a repo
430 430
431 431 It iterates over each part then searches for and uses the proper handling
432 432 code to process the part. Parts are processed in order.
433 433
434 434 Unknown Mandatory part will abort the process.
435 435
436 436 It is temporarily possible to provide a prebuilt bundleoperation to the
437 437 function. This is used to ensure output is properly propagated in case of
438 438 an error during the unbundling. This output capturing part will likely be
439 439 reworked and this ability will probably go away in the process.
440 440 """
441 441 if op is None:
442 442 if transactiongetter is None:
443 443 transactiongetter = _notransaction
444 444 op = bundleoperation(repo, transactiongetter, source=source)
445 445 # todo:
446 446 # - replace this is a init function soon.
447 447 # - exception catching
448 448 unbundler.params
449 449 if repo.ui.debugflag:
450 450 msg = ['bundle2-input-bundle:']
451 451 if unbundler.params:
452 452 msg.append(' %i params' % len(unbundler.params))
453 453 if op._gettransaction is None or op._gettransaction is _notransaction:
454 454 msg.append(' no-transaction')
455 455 else:
456 456 msg.append(' with-transaction')
457 457 msg.append('\n')
458 458 repo.ui.debug(''.join(msg))
459 459
460 460 processparts(repo, op, unbundler)
461 461
462 462 return op
463 463
464 464 def processparts(repo, op, unbundler):
465 465 with partiterator(repo, op, unbundler) as parts:
466 466 for part in parts:
467 467 _processpart(op, part)
468 468
469 469 def _processchangegroup(op, cg, tr, source, url, **kwargs):
470 470 ret = cg.apply(op.repo, tr, source, url, **kwargs)
471 471 op.records.add('changegroup', {
472 472 'return': ret,
473 473 })
474 474 return ret
475 475
476 476 def _gethandler(op, part):
477 477 status = 'unknown' # used by debug output
478 478 try:
479 479 handler = parthandlermapping.get(part.type)
480 480 if handler is None:
481 481 status = 'unsupported-type'
482 482 raise error.BundleUnknownFeatureError(parttype=part.type)
483 483 indebug(op.ui, 'found a handler for part %s' % part.type)
484 484 unknownparams = part.mandatorykeys - handler.params
485 485 if unknownparams:
486 486 unknownparams = list(unknownparams)
487 487 unknownparams.sort()
488 488 status = 'unsupported-params (%s)' % ', '.join(unknownparams)
489 489 raise error.BundleUnknownFeatureError(parttype=part.type,
490 490 params=unknownparams)
491 491 status = 'supported'
492 492 except error.BundleUnknownFeatureError as exc:
493 493 if part.mandatory: # mandatory parts
494 494 raise
495 495 indebug(op.ui, 'ignoring unsupported advisory part %s' % exc)
496 496 return # skip to part processing
497 497 finally:
498 498 if op.ui.debugflag:
499 499 msg = ['bundle2-input-part: "%s"' % part.type]
500 500 if not part.mandatory:
501 501 msg.append(' (advisory)')
502 502 nbmp = len(part.mandatorykeys)
503 503 nbap = len(part.params) - nbmp
504 504 if nbmp or nbap:
505 505 msg.append(' (params:')
506 506 if nbmp:
507 507 msg.append(' %i mandatory' % nbmp)
508 508 if nbap:
509 509 msg.append(' %i advisory' % nbmp)
510 510 msg.append(')')
511 511 msg.append(' %s\n' % status)
512 512 op.ui.debug(''.join(msg))
513 513
514 514 return handler
515 515
516 516 def _processpart(op, part):
517 517 """process a single part from a bundle
518 518
519 519 The part is guaranteed to have been fully consumed when the function exits
520 520 (even if an exception is raised)."""
521 521 handler = _gethandler(op, part)
522 522 if handler is None:
523 523 return
524 524
525 525 # handler is called outside the above try block so that we don't
526 526 # risk catching KeyErrors from anything other than the
527 527 # parthandlermapping lookup (any KeyError raised by handler()
528 528 # itself represents a defect of a different variety).
529 529 output = None
530 530 if op.captureoutput and op.reply is not None:
531 531 op.ui.pushbuffer(error=True, subproc=True)
532 532 output = ''
533 533 try:
534 534 handler(op, part)
535 535 finally:
536 536 if output is not None:
537 537 output = op.ui.popbuffer()
538 538 if output:
539 539 outpart = op.reply.newpart('output', data=output,
540 540 mandatory=False)
541 541 outpart.addparam(
542 542 'in-reply-to', pycompat.bytestr(part.id), mandatory=False)
543 543
544 544 def decodecaps(blob):
545 545 """decode a bundle2 caps bytes blob into a dictionary
546 546
547 547 The blob is a list of capabilities (one per line)
548 548 Capabilities may have values using a line of the form::
549 549
550 550 capability=value1,value2,value3
551 551
552 552 The values are always a list."""
553 553 caps = {}
554 554 for line in blob.splitlines():
555 555 if not line:
556 556 continue
557 557 if '=' not in line:
558 558 key, vals = line, ()
559 559 else:
560 560 key, vals = line.split('=', 1)
561 561 vals = vals.split(',')
562 562 key = urlreq.unquote(key)
563 563 vals = [urlreq.unquote(v) for v in vals]
564 564 caps[key] = vals
565 565 return caps
566 566
567 567 def encodecaps(caps):
568 568 """encode a bundle2 caps dictionary into a bytes blob"""
569 569 chunks = []
570 570 for ca in sorted(caps):
571 571 vals = caps[ca]
572 572 ca = urlreq.quote(ca)
573 573 vals = [urlreq.quote(v) for v in vals]
574 574 if vals:
575 575 ca = "%s=%s" % (ca, ','.join(vals))
576 576 chunks.append(ca)
577 577 return '\n'.join(chunks)
578 578
579 579 bundletypes = {
580 580 "": ("", 'UN'), # only when using unbundle on ssh and old http servers
581 581 # since the unification ssh accepts a header but there
582 582 # is no capability signaling it.
583 583 "HG20": (), # special-cased below
584 584 "HG10UN": ("HG10UN", 'UN'),
585 585 "HG10BZ": ("HG10", 'BZ'),
586 586 "HG10GZ": ("HG10GZ", 'GZ'),
587 587 }
588 588
589 589 # hgweb uses this list to communicate its preferred type
590 590 bundlepriority = ['HG10GZ', 'HG10BZ', 'HG10UN']
591 591
592 592 class bundle20(object):
593 593 """represent an outgoing bundle2 container
594 594
595 595 Use the `addparam` method to add stream level parameter. and `newpart` to
596 596 populate it. Then call `getchunks` to retrieve all the binary chunks of
597 597 data that compose the bundle2 container."""
598 598
599 599 _magicstring = 'HG20'
600 600
601 601 def __init__(self, ui, capabilities=()):
602 602 self.ui = ui
603 603 self._params = []
604 604 self._parts = []
605 605 self.capabilities = dict(capabilities)
606 606 self._compengine = util.compengines.forbundletype('UN')
607 607 self._compopts = None
608 608 # If compression is being handled by a consumer of the raw
609 609 # data (e.g. the wire protocol), unsetting this flag tells
610 610 # consumers that the bundle is best left uncompressed.
611 611 self.prefercompressed = True
612 612
613 613 def setcompression(self, alg, compopts=None):
614 614 """setup core part compression to <alg>"""
615 615 if alg in (None, 'UN'):
616 616 return
617 617 assert not any(n.lower() == 'compression' for n, v in self._params)
618 618 self.addparam('Compression', alg)
619 619 self._compengine = util.compengines.forbundletype(alg)
620 620 self._compopts = compopts
621 621
622 622 @property
623 623 def nbparts(self):
624 624 """total number of parts added to the bundler"""
625 625 return len(self._parts)
626 626
627 627 # methods used to defines the bundle2 content
628 628 def addparam(self, name, value=None):
629 629 """add a stream level parameter"""
630 630 if not name:
631 631 raise error.ProgrammingError(b'empty parameter name')
632 632 if name[0:1] not in pycompat.bytestr(string.ascii_letters):
633 633 raise error.ProgrammingError(b'non letter first character: %s'
634 634 % name)
635 635 self._params.append((name, value))
636 636
637 637 def addpart(self, part):
638 638 """add a new part to the bundle2 container
639 639
640 640 Parts contains the actual applicative payload."""
641 641 assert part.id is None
642 642 part.id = len(self._parts) # very cheap counter
643 643 self._parts.append(part)
644 644
645 645 def newpart(self, typeid, *args, **kwargs):
646 646 """create a new part and add it to the containers
647 647
648 648 As the part is directly added to the containers. For now, this means
649 649 that any failure to properly initialize the part after calling
650 650 ``newpart`` should result in a failure of the whole bundling process.
651 651
652 652 You can still fall back to manually create and add if you need better
653 653 control."""
654 654 part = bundlepart(typeid, *args, **kwargs)
655 655 self.addpart(part)
656 656 return part
657 657
658 658 # methods used to generate the bundle2 stream
659 659 def getchunks(self):
660 660 if self.ui.debugflag:
661 661 msg = ['bundle2-output-bundle: "%s",' % self._magicstring]
662 662 if self._params:
663 663 msg.append(' (%i params)' % len(self._params))
664 664 msg.append(' %i parts total\n' % len(self._parts))
665 665 self.ui.debug(''.join(msg))
666 666 outdebug(self.ui, 'start emission of %s stream' % self._magicstring)
667 667 yield self._magicstring
668 668 param = self._paramchunk()
669 669 outdebug(self.ui, 'bundle parameter: %s' % param)
670 670 yield _pack(_fstreamparamsize, len(param))
671 671 if param:
672 672 yield param
673 673 for chunk in self._compengine.compressstream(self._getcorechunk(),
674 674 self._compopts):
675 675 yield chunk
676 676
677 677 def _paramchunk(self):
678 678 """return a encoded version of all stream parameters"""
679 679 blocks = []
680 680 for par, value in self._params:
681 681 par = urlreq.quote(par)
682 682 if value is not None:
683 683 value = urlreq.quote(value)
684 684 par = '%s=%s' % (par, value)
685 685 blocks.append(par)
686 686 return ' '.join(blocks)
687 687
688 688 def _getcorechunk(self):
689 689 """yield chunk for the core part of the bundle
690 690
691 691 (all but headers and parameters)"""
692 692 outdebug(self.ui, 'start of parts')
693 693 for part in self._parts:
694 694 outdebug(self.ui, 'bundle part: "%s"' % part.type)
695 695 for chunk in part.getchunks(ui=self.ui):
696 696 yield chunk
697 697 outdebug(self.ui, 'end of bundle')
698 698 yield _pack(_fpartheadersize, 0)
699 699
700 700
701 701 def salvageoutput(self):
702 702 """return a list with a copy of all output parts in the bundle
703 703
704 704 This is meant to be used during error handling to make sure we preserve
705 705 server output"""
706 706 salvaged = []
707 707 for part in self._parts:
708 708 if part.type.startswith('output'):
709 709 salvaged.append(part.copy())
710 710 return salvaged
711 711
712 712
713 713 class unpackermixin(object):
714 714 """A mixin to extract bytes and struct data from a stream"""
715 715
716 716 def __init__(self, fp):
717 717 self._fp = fp
718 718
719 719 def _unpack(self, format):
720 720 """unpack this struct format from the stream
721 721
722 722 This method is meant for internal usage by the bundle2 protocol only.
723 723 They directly manipulate the low level stream including bundle2 level
724 724 instruction.
725 725
726 726 Do not use it to implement higher-level logic or methods."""
727 727 data = self._readexact(struct.calcsize(format))
728 728 return _unpack(format, data)
729 729
730 730 def _readexact(self, size):
731 731 """read exactly <size> bytes from the stream
732 732
733 733 This method is meant for internal usage by the bundle2 protocol only.
734 734 They directly manipulate the low level stream including bundle2 level
735 735 instruction.
736 736
737 737 Do not use it to implement higher-level logic or methods."""
738 738 return changegroup.readexactly(self._fp, size)
739 739
740 740 def getunbundler(ui, fp, magicstring=None):
741 741 """return a valid unbundler object for a given magicstring"""
742 742 if magicstring is None:
743 743 magicstring = changegroup.readexactly(fp, 4)
744 744 magic, version = magicstring[0:2], magicstring[2:4]
745 745 if magic != 'HG':
746 746 ui.debug(
747 747 "error: invalid magic: %r (version %r), should be 'HG'\n"
748 748 % (magic, version))
749 749 raise error.Abort(_('not a Mercurial bundle'))
750 750 unbundlerclass = formatmap.get(version)
751 751 if unbundlerclass is None:
752 752 raise error.Abort(_('unknown bundle version %s') % version)
753 753 unbundler = unbundlerclass(ui, fp)
754 754 indebug(ui, 'start processing of %s stream' % magicstring)
755 755 return unbundler
756 756
757 757 class unbundle20(unpackermixin):
758 758 """interpret a bundle2 stream
759 759
760 760 This class is fed with a binary stream and yields parts through its
761 761 `iterparts` methods."""
762 762
763 763 _magicstring = 'HG20'
764 764
765 765 def __init__(self, ui, fp):
766 766 """If header is specified, we do not read it out of the stream."""
767 767 self.ui = ui
768 768 self._compengine = util.compengines.forbundletype('UN')
769 769 self._compressed = None
770 770 super(unbundle20, self).__init__(fp)
771 771
772 772 @util.propertycache
773 773 def params(self):
774 774 """dictionary of stream level parameters"""
775 775 indebug(self.ui, 'reading bundle2 stream parameters')
776 776 params = {}
777 777 paramssize = self._unpack(_fstreamparamsize)[0]
778 778 if paramssize < 0:
779 779 raise error.BundleValueError('negative bundle param size: %i'
780 780 % paramssize)
781 781 if paramssize:
782 782 params = self._readexact(paramssize)
783 783 params = self._processallparams(params)
784 784 return params
785 785
786 786 def _processallparams(self, paramsblock):
787 787 """"""
788 788 params = util.sortdict()
789 789 for p in paramsblock.split(' '):
790 790 p = p.split('=', 1)
791 791 p = [urlreq.unquote(i) for i in p]
792 792 if len(p) < 2:
793 793 p.append(None)
794 794 self._processparam(*p)
795 795 params[p[0]] = p[1]
796 796 return params
797 797
798 798
799 799 def _processparam(self, name, value):
800 800 """process a parameter, applying its effect if needed
801 801
802 802 Parameter starting with a lower case letter are advisory and will be
803 803 ignored when unknown. Those starting with an upper case letter are
804 804 mandatory and will this function will raise a KeyError when unknown.
805 805
806 806 Note: no option are currently supported. Any input will be either
807 807 ignored or failing.
808 808 """
809 809 if not name:
810 810 raise ValueError(r'empty parameter name')
811 811 if name[0:1] not in pycompat.bytestr(string.ascii_letters):
812 812 raise ValueError(r'non letter first character: %s' % name)
813 813 try:
814 814 handler = b2streamparamsmap[name.lower()]
815 815 except KeyError:
816 816 if name[0:1].islower():
817 817 indebug(self.ui, "ignoring unknown parameter %s" % name)
818 818 else:
819 819 raise error.BundleUnknownFeatureError(params=(name,))
820 820 else:
821 821 handler(self, name, value)
822 822
823 823 def _forwardchunks(self):
824 824 """utility to transfer a bundle2 as binary
825 825
826 826 This is made necessary by the fact the 'getbundle' command over 'ssh'
827 827 have no way to know then the reply end, relying on the bundle to be
828 828 interpreted to know its end. This is terrible and we are sorry, but we
829 829 needed to move forward to get general delta enabled.
830 830 """
831 831 yield self._magicstring
832 832 assert 'params' not in vars(self)
833 833 paramssize = self._unpack(_fstreamparamsize)[0]
834 834 if paramssize < 0:
835 835 raise error.BundleValueError('negative bundle param size: %i'
836 836 % paramssize)
837 837 yield _pack(_fstreamparamsize, paramssize)
838 838 if paramssize:
839 839 params = self._readexact(paramssize)
840 840 self._processallparams(params)
841 841 yield params
842 842 assert self._compengine.bundletype()[1] == 'UN'
843 843 # From there, payload might need to be decompressed
844 844 self._fp = self._compengine.decompressorreader(self._fp)
845 845 emptycount = 0
846 846 while emptycount < 2:
847 847 # so we can brainlessly loop
848 848 assert _fpartheadersize == _fpayloadsize
849 849 size = self._unpack(_fpartheadersize)[0]
850 850 yield _pack(_fpartheadersize, size)
851 851 if size:
852 852 emptycount = 0
853 853 else:
854 854 emptycount += 1
855 855 continue
856 856 if size == flaginterrupt:
857 857 continue
858 858 elif size < 0:
859 859 raise error.BundleValueError('negative chunk size: %i')
860 860 yield self._readexact(size)
861 861
862 862
863 863 def iterparts(self, seekable=False):
864 864 """yield all parts contained in the stream"""
865 865 cls = seekableunbundlepart if seekable else unbundlepart
866 866 # make sure param have been loaded
867 867 self.params
868 868 # From there, payload need to be decompressed
869 869 self._fp = self._compengine.decompressorreader(self._fp)
870 870 indebug(self.ui, 'start extraction of bundle2 parts')
871 871 headerblock = self._readpartheader()
872 872 while headerblock is not None:
873 873 part = cls(self.ui, headerblock, self._fp)
874 874 yield part
875 875 # Ensure part is fully consumed so we can start reading the next
876 876 # part.
877 877 part.consume()
878 878
879 879 headerblock = self._readpartheader()
880 880 indebug(self.ui, 'end of bundle2 stream')
881 881
882 882 def _readpartheader(self):
883 883 """reads a part header size and return the bytes blob
884 884
885 885 returns None if empty"""
886 886 headersize = self._unpack(_fpartheadersize)[0]
887 887 if headersize < 0:
888 888 raise error.BundleValueError('negative part header size: %i'
889 889 % headersize)
890 890 indebug(self.ui, 'part header size: %i' % headersize)
891 891 if headersize:
892 892 return self._readexact(headersize)
893 893 return None
894 894
895 895 def compressed(self):
896 896 self.params # load params
897 897 return self._compressed
898 898
899 899 def close(self):
900 900 """close underlying file"""
901 901 if util.safehasattr(self._fp, 'close'):
902 902 return self._fp.close()
903 903
904 904 formatmap = {'20': unbundle20}
905 905
906 906 b2streamparamsmap = {}
907 907
908 908 def b2streamparamhandler(name):
909 909 """register a handler for a stream level parameter"""
910 910 def decorator(func):
911 911 assert name not in formatmap
912 912 b2streamparamsmap[name] = func
913 913 return func
914 914 return decorator
915 915
916 916 @b2streamparamhandler('compression')
917 917 def processcompression(unbundler, param, value):
918 918 """read compression parameter and install payload decompression"""
919 919 if value not in util.compengines.supportedbundletypes:
920 920 raise error.BundleUnknownFeatureError(params=(param,),
921 921 values=(value,))
922 922 unbundler._compengine = util.compengines.forbundletype(value)
923 923 if value is not None:
924 924 unbundler._compressed = True
925 925
926 926 class bundlepart(object):
927 927 """A bundle2 part contains application level payload
928 928
929 929 The part `type` is used to route the part to the application level
930 930 handler.
931 931
932 932 The part payload is contained in ``part.data``. It could be raw bytes or a
933 933 generator of byte chunks.
934 934
935 935 You can add parameters to the part using the ``addparam`` method.
936 936 Parameters can be either mandatory (default) or advisory. Remote side
937 937 should be able to safely ignore the advisory ones.
938 938
939 939 Both data and parameters cannot be modified after the generation has begun.
940 940 """
941 941
942 942 def __init__(self, parttype, mandatoryparams=(), advisoryparams=(),
943 943 data='', mandatory=True):
944 944 validateparttype(parttype)
945 945 self.id = None
946 946 self.type = parttype
947 947 self._data = data
948 948 self._mandatoryparams = list(mandatoryparams)
949 949 self._advisoryparams = list(advisoryparams)
950 950 # checking for duplicated entries
951 951 self._seenparams = set()
952 952 for pname, __ in self._mandatoryparams + self._advisoryparams:
953 953 if pname in self._seenparams:
954 954 raise error.ProgrammingError('duplicated params: %s' % pname)
955 955 self._seenparams.add(pname)
956 956 # status of the part's generation:
957 957 # - None: not started,
958 958 # - False: currently generated,
959 959 # - True: generation done.
960 960 self._generated = None
961 961 self.mandatory = mandatory
962 962
963 963 def __repr__(self):
964 964 cls = "%s.%s" % (self.__class__.__module__, self.__class__.__name__)
965 965 return ('<%s object at %x; id: %s; type: %s; mandatory: %s>'
966 966 % (cls, id(self), self.id, self.type, self.mandatory))
967 967
968 968 def copy(self):
969 969 """return a copy of the part
970 970
971 971 The new part have the very same content but no partid assigned yet.
972 972 Parts with generated data cannot be copied."""
973 973 assert not util.safehasattr(self.data, 'next')
974 974 return self.__class__(self.type, self._mandatoryparams,
975 975 self._advisoryparams, self._data, self.mandatory)
976 976
977 977 # methods used to defines the part content
978 978 @property
979 979 def data(self):
980 980 return self._data
981 981
982 982 @data.setter
983 983 def data(self, data):
984 984 if self._generated is not None:
985 985 raise error.ReadOnlyPartError('part is being generated')
986 986 self._data = data
987 987
988 988 @property
989 989 def mandatoryparams(self):
990 990 # make it an immutable tuple to force people through ``addparam``
991 991 return tuple(self._mandatoryparams)
992 992
993 993 @property
994 994 def advisoryparams(self):
995 995 # make it an immutable tuple to force people through ``addparam``
996 996 return tuple(self._advisoryparams)
997 997
998 998 def addparam(self, name, value='', mandatory=True):
999 999 """add a parameter to the part
1000 1000
1001 1001 If 'mandatory' is set to True, the remote handler must claim support
1002 1002 for this parameter or the unbundling will be aborted.
1003 1003
1004 1004 The 'name' and 'value' cannot exceed 255 bytes each.
1005 1005 """
1006 1006 if self._generated is not None:
1007 1007 raise error.ReadOnlyPartError('part is being generated')
1008 1008 if name in self._seenparams:
1009 1009 raise ValueError('duplicated params: %s' % name)
1010 1010 self._seenparams.add(name)
1011 1011 params = self._advisoryparams
1012 1012 if mandatory:
1013 1013 params = self._mandatoryparams
1014 1014 params.append((name, value))
1015 1015
1016 1016 # methods used to generates the bundle2 stream
1017 1017 def getchunks(self, ui):
1018 1018 if self._generated is not None:
1019 1019 raise error.ProgrammingError('part can only be consumed once')
1020 1020 self._generated = False
1021 1021
1022 1022 if ui.debugflag:
1023 1023 msg = ['bundle2-output-part: "%s"' % self.type]
1024 1024 if not self.mandatory:
1025 1025 msg.append(' (advisory)')
1026 1026 nbmp = len(self.mandatoryparams)
1027 1027 nbap = len(self.advisoryparams)
1028 1028 if nbmp or nbap:
1029 1029 msg.append(' (params:')
1030 1030 if nbmp:
1031 1031 msg.append(' %i mandatory' % nbmp)
1032 1032 if nbap:
1033 1033 msg.append(' %i advisory' % nbmp)
1034 1034 msg.append(')')
1035 1035 if not self.data:
1036 1036 msg.append(' empty payload')
1037 1037 elif (util.safehasattr(self.data, 'next')
1038 1038 or util.safehasattr(self.data, '__next__')):
1039 1039 msg.append(' streamed payload')
1040 1040 else:
1041 1041 msg.append(' %i bytes payload' % len(self.data))
1042 1042 msg.append('\n')
1043 1043 ui.debug(''.join(msg))
1044 1044
1045 1045 #### header
1046 1046 if self.mandatory:
1047 1047 parttype = self.type.upper()
1048 1048 else:
1049 1049 parttype = self.type.lower()
1050 1050 outdebug(ui, 'part %s: "%s"' % (pycompat.bytestr(self.id), parttype))
1051 1051 ## parttype
1052 1052 header = [_pack(_fparttypesize, len(parttype)),
1053 1053 parttype, _pack(_fpartid, self.id),
1054 1054 ]
1055 1055 ## parameters
1056 1056 # count
1057 1057 manpar = self.mandatoryparams
1058 1058 advpar = self.advisoryparams
1059 1059 header.append(_pack(_fpartparamcount, len(manpar), len(advpar)))
1060 1060 # size
1061 1061 parsizes = []
1062 1062 for key, value in manpar:
1063 1063 parsizes.append(len(key))
1064 1064 parsizes.append(len(value))
1065 1065 for key, value in advpar:
1066 1066 parsizes.append(len(key))
1067 1067 parsizes.append(len(value))
1068 1068 paramsizes = _pack(_makefpartparamsizes(len(parsizes) // 2), *parsizes)
1069 1069 header.append(paramsizes)
1070 1070 # key, value
1071 1071 for key, value in manpar:
1072 1072 header.append(key)
1073 1073 header.append(value)
1074 1074 for key, value in advpar:
1075 1075 header.append(key)
1076 1076 header.append(value)
1077 1077 ## finalize header
1078 1078 try:
1079 1079 headerchunk = ''.join(header)
1080 1080 except TypeError:
1081 1081 raise TypeError(r'Found a non-bytes trying to '
1082 1082 r'build bundle part header: %r' % header)
1083 1083 outdebug(ui, 'header chunk size: %i' % len(headerchunk))
1084 1084 yield _pack(_fpartheadersize, len(headerchunk))
1085 1085 yield headerchunk
1086 1086 ## payload
1087 1087 try:
1088 1088 for chunk in self._payloadchunks():
1089 1089 outdebug(ui, 'payload chunk size: %i' % len(chunk))
1090 1090 yield _pack(_fpayloadsize, len(chunk))
1091 1091 yield chunk
1092 1092 except GeneratorExit:
1093 1093 # GeneratorExit means that nobody is listening for our
1094 1094 # results anyway, so just bail quickly rather than trying
1095 1095 # to produce an error part.
1096 1096 ui.debug('bundle2-generatorexit\n')
1097 1097 raise
1098 1098 except BaseException as exc:
1099 1099 bexc = stringutil.forcebytestr(exc)
1100 1100 # backup exception data for later
1101 1101 ui.debug('bundle2-input-stream-interrupt: encoding exception %s'
1102 1102 % bexc)
1103 1103 tb = sys.exc_info()[2]
1104 1104 msg = 'unexpected error: %s' % bexc
1105 1105 interpart = bundlepart('error:abort', [('message', msg)],
1106 1106 mandatory=False)
1107 1107 interpart.id = 0
1108 1108 yield _pack(_fpayloadsize, -1)
1109 1109 for chunk in interpart.getchunks(ui=ui):
1110 1110 yield chunk
1111 1111 outdebug(ui, 'closing payload chunk')
1112 1112 # abort current part payload
1113 1113 yield _pack(_fpayloadsize, 0)
1114 1114 pycompat.raisewithtb(exc, tb)
1115 1115 # end of payload
1116 1116 outdebug(ui, 'closing payload chunk')
1117 1117 yield _pack(_fpayloadsize, 0)
1118 1118 self._generated = True
1119 1119
1120 1120 def _payloadchunks(self):
1121 1121 """yield chunks of a the part payload
1122 1122
1123 1123 Exists to handle the different methods to provide data to a part."""
1124 1124 # we only support fixed size data now.
1125 1125 # This will be improved in the future.
1126 1126 if (util.safehasattr(self.data, 'next')
1127 1127 or util.safehasattr(self.data, '__next__')):
1128 1128 buff = util.chunkbuffer(self.data)
1129 1129 chunk = buff.read(preferedchunksize)
1130 1130 while chunk:
1131 1131 yield chunk
1132 1132 chunk = buff.read(preferedchunksize)
1133 1133 elif len(self.data):
1134 1134 yield self.data
1135 1135
1136 1136
1137 1137 flaginterrupt = -1
1138 1138
1139 1139 class interrupthandler(unpackermixin):
1140 1140 """read one part and process it with restricted capability
1141 1141
1142 1142 This allows to transmit exception raised on the producer size during part
1143 1143 iteration while the consumer is reading a part.
1144 1144
1145 1145 Part processed in this manner only have access to a ui object,"""
1146 1146
1147 1147 def __init__(self, ui, fp):
1148 1148 super(interrupthandler, self).__init__(fp)
1149 1149 self.ui = ui
1150 1150
1151 1151 def _readpartheader(self):
1152 1152 """reads a part header size and return the bytes blob
1153 1153
1154 1154 returns None if empty"""
1155 1155 headersize = self._unpack(_fpartheadersize)[0]
1156 1156 if headersize < 0:
1157 1157 raise error.BundleValueError('negative part header size: %i'
1158 1158 % headersize)
1159 1159 indebug(self.ui, 'part header size: %i\n' % headersize)
1160 1160 if headersize:
1161 1161 return self._readexact(headersize)
1162 1162 return None
1163 1163
1164 1164 def __call__(self):
1165 1165
1166 1166 self.ui.debug('bundle2-input-stream-interrupt:'
1167 1167 ' opening out of band context\n')
1168 1168 indebug(self.ui, 'bundle2 stream interruption, looking for a part.')
1169 1169 headerblock = self._readpartheader()
1170 1170 if headerblock is None:
1171 1171 indebug(self.ui, 'no part found during interruption.')
1172 1172 return
1173 1173 part = unbundlepart(self.ui, headerblock, self._fp)
1174 1174 op = interruptoperation(self.ui)
1175 1175 hardabort = False
1176 1176 try:
1177 1177 _processpart(op, part)
1178 1178 except (SystemExit, KeyboardInterrupt):
1179 1179 hardabort = True
1180 1180 raise
1181 1181 finally:
1182 1182 if not hardabort:
1183 1183 part.consume()
1184 1184 self.ui.debug('bundle2-input-stream-interrupt:'
1185 1185 ' closing out of band context\n')
1186 1186
1187 1187 class interruptoperation(object):
1188 1188 """A limited operation to be use by part handler during interruption
1189 1189
1190 1190 It only have access to an ui object.
1191 1191 """
1192 1192
1193 1193 def __init__(self, ui):
1194 1194 self.ui = ui
1195 1195 self.reply = None
1196 1196 self.captureoutput = False
1197 1197
1198 1198 @property
1199 1199 def repo(self):
1200 1200 raise error.ProgrammingError('no repo access from stream interruption')
1201 1201
1202 1202 def gettransaction(self):
1203 1203 raise TransactionUnavailable('no repo access from stream interruption')
1204 1204
1205 1205 def decodepayloadchunks(ui, fh):
1206 1206 """Reads bundle2 part payload data into chunks.
1207 1207
1208 1208 Part payload data consists of framed chunks. This function takes
1209 1209 a file handle and emits those chunks.
1210 1210 """
1211 1211 dolog = ui.configbool('devel', 'bundle2.debug')
1212 1212 debug = ui.debug
1213 1213
1214 1214 headerstruct = struct.Struct(_fpayloadsize)
1215 1215 headersize = headerstruct.size
1216 1216 unpack = headerstruct.unpack
1217 1217
1218 1218 readexactly = changegroup.readexactly
1219 1219 read = fh.read
1220 1220
1221 1221 chunksize = unpack(readexactly(fh, headersize))[0]
1222 1222 indebug(ui, 'payload chunk size: %i' % chunksize)
1223 1223
1224 1224 # changegroup.readexactly() is inlined below for performance.
1225 1225 while chunksize:
1226 1226 if chunksize >= 0:
1227 1227 s = read(chunksize)
1228 1228 if len(s) < chunksize:
1229 1229 raise error.Abort(_('stream ended unexpectedly '
1230 1230 ' (got %d bytes, expected %d)') %
1231 1231 (len(s), chunksize))
1232 1232
1233 1233 yield s
1234 1234 elif chunksize == flaginterrupt:
1235 1235 # Interrupt "signal" detected. The regular stream is interrupted
1236 1236 # and a bundle2 part follows. Consume it.
1237 1237 interrupthandler(ui, fh)()
1238 1238 else:
1239 1239 raise error.BundleValueError(
1240 1240 'negative payload chunk size: %s' % chunksize)
1241 1241
1242 1242 s = read(headersize)
1243 1243 if len(s) < headersize:
1244 1244 raise error.Abort(_('stream ended unexpectedly '
1245 1245 ' (got %d bytes, expected %d)') %
1246 1246 (len(s), chunksize))
1247 1247
1248 1248 chunksize = unpack(s)[0]
1249 1249
1250 1250 # indebug() inlined for performance.
1251 1251 if dolog:
1252 1252 debug('bundle2-input: payload chunk size: %i\n' % chunksize)
1253 1253
1254 1254 class unbundlepart(unpackermixin):
1255 1255 """a bundle part read from a bundle"""
1256 1256
1257 1257 def __init__(self, ui, header, fp):
1258 1258 super(unbundlepart, self).__init__(fp)
1259 1259 self._seekable = (util.safehasattr(fp, 'seek') and
1260 1260 util.safehasattr(fp, 'tell'))
1261 1261 self.ui = ui
1262 1262 # unbundle state attr
1263 1263 self._headerdata = header
1264 1264 self._headeroffset = 0
1265 1265 self._initialized = False
1266 1266 self.consumed = False
1267 1267 # part data
1268 1268 self.id = None
1269 1269 self.type = None
1270 1270 self.mandatoryparams = None
1271 1271 self.advisoryparams = None
1272 1272 self.params = None
1273 1273 self.mandatorykeys = ()
1274 1274 self._readheader()
1275 1275 self._mandatory = None
1276 1276 self._pos = 0
1277 1277
1278 1278 def _fromheader(self, size):
1279 1279 """return the next <size> byte from the header"""
1280 1280 offset = self._headeroffset
1281 1281 data = self._headerdata[offset:(offset + size)]
1282 1282 self._headeroffset = offset + size
1283 1283 return data
1284 1284
1285 1285 def _unpackheader(self, format):
1286 1286 """read given format from header
1287 1287
1288 1288 This automatically compute the size of the format to read."""
1289 1289 data = self._fromheader(struct.calcsize(format))
1290 1290 return _unpack(format, data)
1291 1291
1292 1292 def _initparams(self, mandatoryparams, advisoryparams):
1293 1293 """internal function to setup all logic related parameters"""
1294 1294 # make it read only to prevent people touching it by mistake.
1295 1295 self.mandatoryparams = tuple(mandatoryparams)
1296 1296 self.advisoryparams = tuple(advisoryparams)
1297 1297 # user friendly UI
1298 1298 self.params = util.sortdict(self.mandatoryparams)
1299 1299 self.params.update(self.advisoryparams)
1300 1300 self.mandatorykeys = frozenset(p[0] for p in mandatoryparams)
1301 1301
1302 1302 def _readheader(self):
1303 1303 """read the header and setup the object"""
1304 1304 typesize = self._unpackheader(_fparttypesize)[0]
1305 1305 self.type = self._fromheader(typesize)
1306 1306 indebug(self.ui, 'part type: "%s"' % self.type)
1307 1307 self.id = self._unpackheader(_fpartid)[0]
1308 1308 indebug(self.ui, 'part id: "%s"' % pycompat.bytestr(self.id))
1309 1309 # extract mandatory bit from type
1310 1310 self.mandatory = (self.type != self.type.lower())
1311 1311 self.type = self.type.lower()
1312 1312 ## reading parameters
1313 1313 # param count
1314 1314 mancount, advcount = self._unpackheader(_fpartparamcount)
1315 1315 indebug(self.ui, 'part parameters: %i' % (mancount + advcount))
1316 1316 # param size
1317 1317 fparamsizes = _makefpartparamsizes(mancount + advcount)
1318 1318 paramsizes = self._unpackheader(fparamsizes)
1319 1319 # make it a list of couple again
1320 1320 paramsizes = list(zip(paramsizes[::2], paramsizes[1::2]))
1321 1321 # split mandatory from advisory
1322 1322 mansizes = paramsizes[:mancount]
1323 1323 advsizes = paramsizes[mancount:]
1324 1324 # retrieve param value
1325 1325 manparams = []
1326 1326 for key, value in mansizes:
1327 1327 manparams.append((self._fromheader(key), self._fromheader(value)))
1328 1328 advparams = []
1329 1329 for key, value in advsizes:
1330 1330 advparams.append((self._fromheader(key), self._fromheader(value)))
1331 1331 self._initparams(manparams, advparams)
1332 1332 ## part payload
1333 1333 self._payloadstream = util.chunkbuffer(self._payloadchunks())
1334 1334 # we read the data, tell it
1335 1335 self._initialized = True
1336 1336
1337 1337 def _payloadchunks(self):
1338 1338 """Generator of decoded chunks in the payload."""
1339 1339 return decodepayloadchunks(self.ui, self._fp)
1340 1340
1341 1341 def consume(self):
1342 1342 """Read the part payload until completion.
1343 1343
1344 1344 By consuming the part data, the underlying stream read offset will
1345 1345 be advanced to the next part (or end of stream).
1346 1346 """
1347 1347 if self.consumed:
1348 1348 return
1349 1349
1350 1350 chunk = self.read(32768)
1351 1351 while chunk:
1352 1352 self._pos += len(chunk)
1353 1353 chunk = self.read(32768)
1354 1354
1355 1355 def read(self, size=None):
1356 1356 """read payload data"""
1357 1357 if not self._initialized:
1358 1358 self._readheader()
1359 1359 if size is None:
1360 1360 data = self._payloadstream.read()
1361 1361 else:
1362 1362 data = self._payloadstream.read(size)
1363 1363 self._pos += len(data)
1364 1364 if size is None or len(data) < size:
1365 1365 if not self.consumed and self._pos:
1366 1366 self.ui.debug('bundle2-input-part: total payload size %i\n'
1367 1367 % self._pos)
1368 1368 self.consumed = True
1369 1369 return data
1370 1370
1371 1371 class seekableunbundlepart(unbundlepart):
1372 1372 """A bundle2 part in a bundle that is seekable.
1373 1373
1374 1374 Regular ``unbundlepart`` instances can only be read once. This class
1375 1375 extends ``unbundlepart`` to enable bi-directional seeking within the
1376 1376 part.
1377 1377
1378 1378 Bundle2 part data consists of framed chunks. Offsets when seeking
1379 1379 refer to the decoded data, not the offsets in the underlying bundle2
1380 1380 stream.
1381 1381
1382 1382 To facilitate quickly seeking within the decoded data, instances of this
1383 1383 class maintain a mapping between offsets in the underlying stream and
1384 1384 the decoded payload. This mapping will consume memory in proportion
1385 1385 to the number of chunks within the payload (which almost certainly
1386 1386 increases in proportion with the size of the part).
1387 1387 """
1388 1388 def __init__(self, ui, header, fp):
1389 1389 # (payload, file) offsets for chunk starts.
1390 1390 self._chunkindex = []
1391 1391
1392 1392 super(seekableunbundlepart, self).__init__(ui, header, fp)
1393 1393
1394 1394 def _payloadchunks(self, chunknum=0):
1395 1395 '''seek to specified chunk and start yielding data'''
1396 1396 if len(self._chunkindex) == 0:
1397 1397 assert chunknum == 0, 'Must start with chunk 0'
1398 1398 self._chunkindex.append((0, self._tellfp()))
1399 1399 else:
1400 1400 assert chunknum < len(self._chunkindex), \
1401 1401 'Unknown chunk %d' % chunknum
1402 1402 self._seekfp(self._chunkindex[chunknum][1])
1403 1403
1404 1404 pos = self._chunkindex[chunknum][0]
1405 1405
1406 1406 for chunk in decodepayloadchunks(self.ui, self._fp):
1407 1407 chunknum += 1
1408 1408 pos += len(chunk)
1409 1409 if chunknum == len(self._chunkindex):
1410 1410 self._chunkindex.append((pos, self._tellfp()))
1411 1411
1412 1412 yield chunk
1413 1413
1414 1414 def _findchunk(self, pos):
1415 1415 '''for a given payload position, return a chunk number and offset'''
1416 1416 for chunk, (ppos, fpos) in enumerate(self._chunkindex):
1417 1417 if ppos == pos:
1418 1418 return chunk, 0
1419 1419 elif ppos > pos:
1420 1420 return chunk - 1, pos - self._chunkindex[chunk - 1][0]
1421 1421 raise ValueError('Unknown chunk')
1422 1422
1423 1423 def tell(self):
1424 1424 return self._pos
1425 1425
1426 1426 def seek(self, offset, whence=os.SEEK_SET):
1427 1427 if whence == os.SEEK_SET:
1428 1428 newpos = offset
1429 1429 elif whence == os.SEEK_CUR:
1430 1430 newpos = self._pos + offset
1431 1431 elif whence == os.SEEK_END:
1432 1432 if not self.consumed:
1433 1433 # Can't use self.consume() here because it advances self._pos.
1434 1434 chunk = self.read(32768)
1435 1435 while chunk:
1436 1436 chunk = self.read(32768)
1437 1437 newpos = self._chunkindex[-1][0] - offset
1438 1438 else:
1439 1439 raise ValueError('Unknown whence value: %r' % (whence,))
1440 1440
1441 1441 if newpos > self._chunkindex[-1][0] and not self.consumed:
1442 1442 # Can't use self.consume() here because it advances self._pos.
1443 1443 chunk = self.read(32768)
1444 1444 while chunk:
1445 1445 chunk = self.read(32668)
1446 1446
1447 1447 if not 0 <= newpos <= self._chunkindex[-1][0]:
1448 1448 raise ValueError('Offset out of range')
1449 1449
1450 1450 if self._pos != newpos:
1451 1451 chunk, internaloffset = self._findchunk(newpos)
1452 1452 self._payloadstream = util.chunkbuffer(self._payloadchunks(chunk))
1453 1453 adjust = self.read(internaloffset)
1454 1454 if len(adjust) != internaloffset:
1455 1455 raise error.Abort(_('Seek failed\n'))
1456 1456 self._pos = newpos
1457 1457
1458 1458 def _seekfp(self, offset, whence=0):
1459 1459 """move the underlying file pointer
1460 1460
1461 1461 This method is meant for internal usage by the bundle2 protocol only.
1462 1462 They directly manipulate the low level stream including bundle2 level
1463 1463 instruction.
1464 1464
1465 1465 Do not use it to implement higher-level logic or methods."""
1466 1466 if self._seekable:
1467 1467 return self._fp.seek(offset, whence)
1468 1468 else:
1469 1469 raise NotImplementedError(_('File pointer is not seekable'))
1470 1470
1471 1471 def _tellfp(self):
1472 1472 """return the file offset, or None if file is not seekable
1473 1473
1474 1474 This method is meant for internal usage by the bundle2 protocol only.
1475 1475 They directly manipulate the low level stream including bundle2 level
1476 1476 instruction.
1477 1477
1478 1478 Do not use it to implement higher-level logic or methods."""
1479 1479 if self._seekable:
1480 1480 try:
1481 1481 return self._fp.tell()
1482 1482 except IOError as e:
1483 1483 if e.errno == errno.ESPIPE:
1484 1484 self._seekable = False
1485 1485 else:
1486 1486 raise
1487 1487 return None
1488 1488
1489 1489 # These are only the static capabilities.
1490 1490 # Check the 'getrepocaps' function for the rest.
1491 1491 capabilities = {'HG20': (),
1492 1492 'bookmarks': (),
1493 1493 'error': ('abort', 'unsupportedcontent', 'pushraced',
1494 1494 'pushkey'),
1495 1495 'listkeys': (),
1496 1496 'pushkey': (),
1497 1497 'digests': tuple(sorted(util.DIGESTS.keys())),
1498 1498 'remote-changegroup': ('http', 'https'),
1499 1499 'hgtagsfnodes': (),
1500 1500 'rev-branch-cache': (),
1501 1501 'phases': ('heads',),
1502 1502 'stream': ('v2',),
1503 1503 }
1504 1504
1505 1505 def getrepocaps(repo, allowpushback=False, role=None):
1506 1506 """return the bundle2 capabilities for a given repo
1507 1507
1508 1508 Exists to allow extensions (like evolution) to mutate the capabilities.
1509 1509
1510 1510 The returned value is used for servers advertising their capabilities as
1511 1511 well as clients advertising their capabilities to servers as part of
1512 1512 bundle2 requests. The ``role`` argument specifies which is which.
1513 1513 """
1514 1514 if role not in ('client', 'server'):
1515 1515 raise error.ProgrammingError('role argument must be client or server')
1516 1516
1517 1517 caps = capabilities.copy()
1518 1518 caps['changegroup'] = tuple(sorted(
1519 1519 changegroup.supportedincomingversions(repo)))
1520 1520 if obsolete.isenabled(repo, obsolete.exchangeopt):
1521 1521 supportedformat = tuple('V%i' % v for v in obsolete.formats)
1522 1522 caps['obsmarkers'] = supportedformat
1523 1523 if allowpushback:
1524 1524 caps['pushback'] = ()
1525 1525 cpmode = repo.ui.config('server', 'concurrent-push-mode')
1526 1526 if cpmode == 'check-related':
1527 1527 caps['checkheads'] = ('related',)
1528 1528 if 'phases' in repo.ui.configlist('devel', 'legacy.exchange'):
1529 1529 caps.pop('phases')
1530 1530
1531 1531 # Don't advertise stream clone support in server mode if not configured.
1532 1532 if role == 'server':
1533 1533 streamsupported = repo.ui.configbool('server', 'uncompressed',
1534 1534 untrusted=True)
1535 1535 featuresupported = repo.ui.configbool('server', 'bundle2.stream')
1536 1536
1537 1537 if not streamsupported or not featuresupported:
1538 1538 caps.pop('stream')
1539 1539 # Else always advertise support on client, because payload support
1540 1540 # should always be advertised.
1541 1541
1542 1542 return caps
1543 1543
1544 1544 def bundle2caps(remote):
1545 1545 """return the bundle capabilities of a peer as dict"""
1546 1546 raw = remote.capable('bundle2')
1547 1547 if not raw and raw != '':
1548 1548 return {}
1549 1549 capsblob = urlreq.unquote(remote.capable('bundle2'))
1550 1550 return decodecaps(capsblob)
1551 1551
1552 1552 def obsmarkersversion(caps):
1553 1553 """extract the list of supported obsmarkers versions from a bundle2caps dict
1554 1554 """
1555 1555 obscaps = caps.get('obsmarkers', ())
1556 1556 return [int(c[1:]) for c in obscaps if c.startswith('V')]
1557 1557
1558 1558 def writenewbundle(ui, repo, source, filename, bundletype, outgoing, opts,
1559 1559 vfs=None, compression=None, compopts=None):
1560 1560 if bundletype.startswith('HG10'):
1561 1561 cg = changegroup.makechangegroup(repo, outgoing, '01', source)
1562 1562 return writebundle(ui, cg, filename, bundletype, vfs=vfs,
1563 1563 compression=compression, compopts=compopts)
1564 1564 elif not bundletype.startswith('HG20'):
1565 1565 raise error.ProgrammingError('unknown bundle type: %s' % bundletype)
1566 1566
1567 1567 caps = {}
1568 1568 if 'obsolescence' in opts:
1569 1569 caps['obsmarkers'] = ('V1',)
1570 1570 bundle = bundle20(ui, caps)
1571 1571 bundle.setcompression(compression, compopts)
1572 1572 _addpartsfromopts(ui, repo, bundle, source, outgoing, opts)
1573 1573 chunkiter = bundle.getchunks()
1574 1574
1575 1575 return changegroup.writechunks(ui, chunkiter, filename, vfs=vfs)
1576 1576
1577 1577 def _addpartsfromopts(ui, repo, bundler, source, outgoing, opts):
1578 1578 # We should eventually reconcile this logic with the one behind
1579 1579 # 'exchange.getbundle2partsgenerator'.
1580 1580 #
1581 1581 # The type of input from 'getbundle' and 'writenewbundle' are a bit
1582 1582 # different right now. So we keep them separated for now for the sake of
1583 1583 # simplicity.
1584 1584
1585 1585 # we might not always want a changegroup in such bundle, for example in
1586 1586 # stream bundles
1587 1587 if opts.get('changegroup', True):
1588 1588 cgversion = opts.get('cg.version')
1589 1589 if cgversion is None:
1590 1590 cgversion = changegroup.safeversion(repo)
1591 1591 cg = changegroup.makechangegroup(repo, outgoing, cgversion, source)
1592 1592 part = bundler.newpart('changegroup', data=cg.getchunks())
1593 1593 part.addparam('version', cg.version)
1594 1594 if 'clcount' in cg.extras:
1595 1595 part.addparam('nbchanges', '%d' % cg.extras['clcount'],
1596 1596 mandatory=False)
1597 1597 if opts.get('phases') and repo.revs('%ln and secret()',
1598 1598 outgoing.missingheads):
1599 1599 part.addparam('targetphase', '%d' % phases.secret, mandatory=False)
1600 1600
1601 1601 if opts.get('streamv2', False):
1602 1602 addpartbundlestream2(bundler, repo, stream=True)
1603 1603
1604 1604 if opts.get('tagsfnodescache', True):
1605 1605 addparttagsfnodescache(repo, bundler, outgoing)
1606 1606
1607 1607 if opts.get('revbranchcache', True):
1608 1608 addpartrevbranchcache(repo, bundler, outgoing)
1609 1609
1610 1610 if opts.get('obsolescence', False):
1611 1611 obsmarkers = repo.obsstore.relevantmarkers(outgoing.missing)
1612 1612 buildobsmarkerspart(bundler, obsmarkers)
1613 1613
1614 1614 if opts.get('phases', False):
1615 1615 headsbyphase = phases.subsetphaseheads(repo, outgoing.missing)
1616 1616 phasedata = phases.binaryencode(headsbyphase)
1617 1617 bundler.newpart('phase-heads', data=phasedata)
1618 1618
1619 1619 def addparttagsfnodescache(repo, bundler, outgoing):
1620 1620 # we include the tags fnode cache for the bundle changeset
1621 1621 # (as an optional parts)
1622 1622 cache = tags.hgtagsfnodescache(repo.unfiltered())
1623 1623 chunks = []
1624 1624
1625 1625 # .hgtags fnodes are only relevant for head changesets. While we could
1626 1626 # transfer values for all known nodes, there will likely be little to
1627 1627 # no benefit.
1628 1628 #
1629 1629 # We don't bother using a generator to produce output data because
1630 1630 # a) we only have 40 bytes per head and even esoteric numbers of heads
1631 1631 # consume little memory (1M heads is 40MB) b) we don't want to send the
1632 1632 # part if we don't have entries and knowing if we have entries requires
1633 1633 # cache lookups.
1634 1634 for node in outgoing.missingheads:
1635 1635 # Don't compute missing, as this may slow down serving.
1636 1636 fnode = cache.getfnode(node, computemissing=False)
1637 1637 if fnode is not None:
1638 1638 chunks.extend([node, fnode])
1639 1639
1640 1640 if chunks:
1641 1641 bundler.newpart('hgtagsfnodes', data=''.join(chunks))
1642 1642
1643 1643 def addpartrevbranchcache(repo, bundler, outgoing):
1644 1644 # we include the rev branch cache for the bundle changeset
1645 1645 # (as an optional parts)
1646 1646 cache = repo.revbranchcache()
1647 1647 cl = repo.unfiltered().changelog
1648 1648 branchesdata = collections.defaultdict(lambda: (set(), set()))
1649 1649 for node in outgoing.missing:
1650 1650 branch, close = cache.branchinfo(cl.rev(node))
1651 1651 branchesdata[branch][close].add(node)
1652 1652
1653 1653 def generate():
1654 1654 for branch, (nodes, closed) in sorted(branchesdata.items()):
1655 1655 utf8branch = encoding.fromlocal(branch)
1656 1656 yield rbcstruct.pack(len(utf8branch), len(nodes), len(closed))
1657 1657 yield utf8branch
1658 1658 for n in sorted(nodes):
1659 1659 yield n
1660 1660 for n in sorted(closed):
1661 1661 yield n
1662 1662
1663 1663 bundler.newpart('cache:rev-branch-cache', data=generate(),
1664 1664 mandatory=False)
1665 1665
1666 1666 def _formatrequirementsspec(requirements):
1667 1667 return urlreq.quote(','.join(sorted(requirements)))
1668 1668
1669 1669 def _formatrequirementsparams(requirements):
1670 1670 requirements = _formatrequirementsspec(requirements)
1671 1671 params = "%s%s" % (urlreq.quote("requirements="), requirements)
1672 1672 return params
1673 1673
1674 1674 def addpartbundlestream2(bundler, repo, **kwargs):
1675 1675 if not kwargs.get(r'stream', False):
1676 1676 return
1677 1677
1678 1678 if not streamclone.allowservergeneration(repo):
1679 1679 raise error.Abort(_('stream data requested but server does not allow '
1680 1680 'this feature'),
1681 1681 hint=_('well-behaved clients should not be '
1682 1682 'requesting stream data from servers not '
1683 1683 'advertising it; the client may be buggy'))
1684 1684
1685 1685 # Stream clones don't compress well. And compression undermines a
1686 1686 # goal of stream clones, which is to be fast. Communicate the desire
1687 1687 # to avoid compression to consumers of the bundle.
1688 1688 bundler.prefercompressed = False
1689 1689
1690 1690 # get the includes and excludes
1691 1691 includepats = kwargs.get(r'includepats')
1692 1692 excludepats = kwargs.get(r'excludepats')
1693 1693
1694 1694 narrowstream = repo.ui.configbool('experimental.server',
1695 1695 'stream-narrow-clones')
1696 1696
1697 1697 if (includepats or excludepats) and not narrowstream:
1698 1698 raise error.Abort(_('server does not support narrow stream clones'))
1699 1699
1700 includeobsmarkers = False
1701 if repo.obsstore:
1702 remoteversions = obsmarkersversion(bundler.capabilities)
1703 if repo.obsstore._version in remoteversions:
1704 includeobsmarkers = True
1705
1700 1706 filecount, bytecount, it = streamclone.generatev2(repo, includepats,
1701 excludepats)
1707 excludepats,
1708 includeobsmarkers)
1702 1709 requirements = _formatrequirementsspec(repo.requirements)
1703 1710 part = bundler.newpart('stream2', data=it)
1704 1711 part.addparam('bytecount', '%d' % bytecount, mandatory=True)
1705 1712 part.addparam('filecount', '%d' % filecount, mandatory=True)
1706 1713 part.addparam('requirements', requirements, mandatory=True)
1707 1714
1708 1715 def buildobsmarkerspart(bundler, markers):
1709 1716 """add an obsmarker part to the bundler with <markers>
1710 1717
1711 1718 No part is created if markers is empty.
1712 1719 Raises ValueError if the bundler doesn't support any known obsmarker format.
1713 1720 """
1714 1721 if not markers:
1715 1722 return None
1716 1723
1717 1724 remoteversions = obsmarkersversion(bundler.capabilities)
1718 1725 version = obsolete.commonversion(remoteversions)
1719 1726 if version is None:
1720 1727 raise ValueError('bundler does not support common obsmarker format')
1721 1728 stream = obsolete.encodemarkers(markers, True, version=version)
1722 1729 return bundler.newpart('obsmarkers', data=stream)
1723 1730
1724 1731 def writebundle(ui, cg, filename, bundletype, vfs=None, compression=None,
1725 1732 compopts=None):
1726 1733 """Write a bundle file and return its filename.
1727 1734
1728 1735 Existing files will not be overwritten.
1729 1736 If no filename is specified, a temporary file is created.
1730 1737 bz2 compression can be turned off.
1731 1738 The bundle file will be deleted in case of errors.
1732 1739 """
1733 1740
1734 1741 if bundletype == "HG20":
1735 1742 bundle = bundle20(ui)
1736 1743 bundle.setcompression(compression, compopts)
1737 1744 part = bundle.newpart('changegroup', data=cg.getchunks())
1738 1745 part.addparam('version', cg.version)
1739 1746 if 'clcount' in cg.extras:
1740 1747 part.addparam('nbchanges', '%d' % cg.extras['clcount'],
1741 1748 mandatory=False)
1742 1749 chunkiter = bundle.getchunks()
1743 1750 else:
1744 1751 # compression argument is only for the bundle2 case
1745 1752 assert compression is None
1746 1753 if cg.version != '01':
1747 1754 raise error.Abort(_('old bundle types only supports v1 '
1748 1755 'changegroups'))
1749 1756 header, comp = bundletypes[bundletype]
1750 1757 if comp not in util.compengines.supportedbundletypes:
1751 1758 raise error.Abort(_('unknown stream compression type: %s')
1752 1759 % comp)
1753 1760 compengine = util.compengines.forbundletype(comp)
1754 1761 def chunkiter():
1755 1762 yield header
1756 1763 for chunk in compengine.compressstream(cg.getchunks(), compopts):
1757 1764 yield chunk
1758 1765 chunkiter = chunkiter()
1759 1766
1760 1767 # parse the changegroup data, otherwise we will block
1761 1768 # in case of sshrepo because we don't know the end of the stream
1762 1769 return changegroup.writechunks(ui, chunkiter, filename, vfs=vfs)
1763 1770
1764 1771 def combinechangegroupresults(op):
1765 1772 """logic to combine 0 or more addchangegroup results into one"""
1766 1773 results = [r.get('return', 0)
1767 1774 for r in op.records['changegroup']]
1768 1775 changedheads = 0
1769 1776 result = 1
1770 1777 for ret in results:
1771 1778 # If any changegroup result is 0, return 0
1772 1779 if ret == 0:
1773 1780 result = 0
1774 1781 break
1775 1782 if ret < -1:
1776 1783 changedheads += ret + 1
1777 1784 elif ret > 1:
1778 1785 changedheads += ret - 1
1779 1786 if changedheads > 0:
1780 1787 result = 1 + changedheads
1781 1788 elif changedheads < 0:
1782 1789 result = -1 + changedheads
1783 1790 return result
1784 1791
1785 1792 @parthandler('changegroup', ('version', 'nbchanges', 'treemanifest',
1786 1793 'targetphase'))
1787 1794 def handlechangegroup(op, inpart):
1788 1795 """apply a changegroup part on the repo
1789 1796
1790 1797 This is a very early implementation that will massive rework before being
1791 1798 inflicted to any end-user.
1792 1799 """
1793 1800 from . import localrepo
1794 1801
1795 1802 tr = op.gettransaction()
1796 1803 unpackerversion = inpart.params.get('version', '01')
1797 1804 # We should raise an appropriate exception here
1798 1805 cg = changegroup.getunbundler(unpackerversion, inpart, None)
1799 1806 # the source and url passed here are overwritten by the one contained in
1800 1807 # the transaction.hookargs argument. So 'bundle2' is a placeholder
1801 1808 nbchangesets = None
1802 1809 if 'nbchanges' in inpart.params:
1803 1810 nbchangesets = int(inpart.params.get('nbchanges'))
1804 1811 if ('treemanifest' in inpart.params and
1805 1812 'treemanifest' not in op.repo.requirements):
1806 1813 if len(op.repo.changelog) != 0:
1807 1814 raise error.Abort(_(
1808 1815 "bundle contains tree manifests, but local repo is "
1809 1816 "non-empty and does not use tree manifests"))
1810 1817 op.repo.requirements.add('treemanifest')
1811 1818 op.repo.svfs.options = localrepo.resolvestorevfsoptions(
1812 1819 op.repo.ui, op.repo.requirements, op.repo.features)
1813 1820 op.repo._writerequirements()
1814 1821 extrakwargs = {}
1815 1822 targetphase = inpart.params.get('targetphase')
1816 1823 if targetphase is not None:
1817 1824 extrakwargs[r'targetphase'] = int(targetphase)
1818 1825 ret = _processchangegroup(op, cg, tr, 'bundle2', 'bundle2',
1819 1826 expectedtotal=nbchangesets, **extrakwargs)
1820 1827 if op.reply is not None:
1821 1828 # This is definitely not the final form of this
1822 1829 # return. But one need to start somewhere.
1823 1830 part = op.reply.newpart('reply:changegroup', mandatory=False)
1824 1831 part.addparam(
1825 1832 'in-reply-to', pycompat.bytestr(inpart.id), mandatory=False)
1826 1833 part.addparam('return', '%i' % ret, mandatory=False)
1827 1834 assert not inpart.read()
1828 1835
1829 1836 _remotechangegroupparams = tuple(['url', 'size', 'digests'] +
1830 1837 ['digest:%s' % k for k in util.DIGESTS.keys()])
1831 1838 @parthandler('remote-changegroup', _remotechangegroupparams)
1832 1839 def handleremotechangegroup(op, inpart):
1833 1840 """apply a bundle10 on the repo, given an url and validation information
1834 1841
1835 1842 All the information about the remote bundle to import are given as
1836 1843 parameters. The parameters include:
1837 1844 - url: the url to the bundle10.
1838 1845 - size: the bundle10 file size. It is used to validate what was
1839 1846 retrieved by the client matches the server knowledge about the bundle.
1840 1847 - digests: a space separated list of the digest types provided as
1841 1848 parameters.
1842 1849 - digest:<digest-type>: the hexadecimal representation of the digest with
1843 1850 that name. Like the size, it is used to validate what was retrieved by
1844 1851 the client matches what the server knows about the bundle.
1845 1852
1846 1853 When multiple digest types are given, all of them are checked.
1847 1854 """
1848 1855 try:
1849 1856 raw_url = inpart.params['url']
1850 1857 except KeyError:
1851 1858 raise error.Abort(_('remote-changegroup: missing "%s" param') % 'url')
1852 1859 parsed_url = util.url(raw_url)
1853 1860 if parsed_url.scheme not in capabilities['remote-changegroup']:
1854 1861 raise error.Abort(_('remote-changegroup does not support %s urls') %
1855 1862 parsed_url.scheme)
1856 1863
1857 1864 try:
1858 1865 size = int(inpart.params['size'])
1859 1866 except ValueError:
1860 1867 raise error.Abort(_('remote-changegroup: invalid value for param "%s"')
1861 1868 % 'size')
1862 1869 except KeyError:
1863 1870 raise error.Abort(_('remote-changegroup: missing "%s" param') % 'size')
1864 1871
1865 1872 digests = {}
1866 1873 for typ in inpart.params.get('digests', '').split():
1867 1874 param = 'digest:%s' % typ
1868 1875 try:
1869 1876 value = inpart.params[param]
1870 1877 except KeyError:
1871 1878 raise error.Abort(_('remote-changegroup: missing "%s" param') %
1872 1879 param)
1873 1880 digests[typ] = value
1874 1881
1875 1882 real_part = util.digestchecker(url.open(op.ui, raw_url), size, digests)
1876 1883
1877 1884 tr = op.gettransaction()
1878 1885 from . import exchange
1879 1886 cg = exchange.readbundle(op.repo.ui, real_part, raw_url)
1880 1887 if not isinstance(cg, changegroup.cg1unpacker):
1881 1888 raise error.Abort(_('%s: not a bundle version 1.0') %
1882 1889 util.hidepassword(raw_url))
1883 1890 ret = _processchangegroup(op, cg, tr, 'bundle2', 'bundle2')
1884 1891 if op.reply is not None:
1885 1892 # This is definitely not the final form of this
1886 1893 # return. But one need to start somewhere.
1887 1894 part = op.reply.newpart('reply:changegroup')
1888 1895 part.addparam(
1889 1896 'in-reply-to', pycompat.bytestr(inpart.id), mandatory=False)
1890 1897 part.addparam('return', '%i' % ret, mandatory=False)
1891 1898 try:
1892 1899 real_part.validate()
1893 1900 except error.Abort as e:
1894 1901 raise error.Abort(_('bundle at %s is corrupted:\n%s') %
1895 1902 (util.hidepassword(raw_url), bytes(e)))
1896 1903 assert not inpart.read()
1897 1904
1898 1905 @parthandler('reply:changegroup', ('return', 'in-reply-to'))
1899 1906 def handlereplychangegroup(op, inpart):
1900 1907 ret = int(inpart.params['return'])
1901 1908 replyto = int(inpart.params['in-reply-to'])
1902 1909 op.records.add('changegroup', {'return': ret}, replyto)
1903 1910
1904 1911 @parthandler('check:bookmarks')
1905 1912 def handlecheckbookmarks(op, inpart):
1906 1913 """check location of bookmarks
1907 1914
1908 1915 This part is to be used to detect push race regarding bookmark, it
1909 1916 contains binary encoded (bookmark, node) tuple. If the local state does
1910 1917 not marks the one in the part, a PushRaced exception is raised
1911 1918 """
1912 1919 bookdata = bookmarks.binarydecode(inpart)
1913 1920
1914 1921 msgstandard = ('remote repository changed while pushing - please try again '
1915 1922 '(bookmark "%s" move from %s to %s)')
1916 1923 msgmissing = ('remote repository changed while pushing - please try again '
1917 1924 '(bookmark "%s" is missing, expected %s)')
1918 1925 msgexist = ('remote repository changed while pushing - please try again '
1919 1926 '(bookmark "%s" set on %s, expected missing)')
1920 1927 for book, node in bookdata:
1921 1928 currentnode = op.repo._bookmarks.get(book)
1922 1929 if currentnode != node:
1923 1930 if node is None:
1924 1931 finalmsg = msgexist % (book, nodemod.short(currentnode))
1925 1932 elif currentnode is None:
1926 1933 finalmsg = msgmissing % (book, nodemod.short(node))
1927 1934 else:
1928 1935 finalmsg = msgstandard % (book, nodemod.short(node),
1929 1936 nodemod.short(currentnode))
1930 1937 raise error.PushRaced(finalmsg)
1931 1938
1932 1939 @parthandler('check:heads')
1933 1940 def handlecheckheads(op, inpart):
1934 1941 """check that head of the repo did not change
1935 1942
1936 1943 This is used to detect a push race when using unbundle.
1937 1944 This replaces the "heads" argument of unbundle."""
1938 1945 h = inpart.read(20)
1939 1946 heads = []
1940 1947 while len(h) == 20:
1941 1948 heads.append(h)
1942 1949 h = inpart.read(20)
1943 1950 assert not h
1944 1951 # Trigger a transaction so that we are guaranteed to have the lock now.
1945 1952 if op.ui.configbool('experimental', 'bundle2lazylocking'):
1946 1953 op.gettransaction()
1947 1954 if sorted(heads) != sorted(op.repo.heads()):
1948 1955 raise error.PushRaced('remote repository changed while pushing - '
1949 1956 'please try again')
1950 1957
1951 1958 @parthandler('check:updated-heads')
1952 1959 def handlecheckupdatedheads(op, inpart):
1953 1960 """check for race on the heads touched by a push
1954 1961
1955 1962 This is similar to 'check:heads' but focus on the heads actually updated
1956 1963 during the push. If other activities happen on unrelated heads, it is
1957 1964 ignored.
1958 1965
1959 1966 This allow server with high traffic to avoid push contention as long as
1960 1967 unrelated parts of the graph are involved."""
1961 1968 h = inpart.read(20)
1962 1969 heads = []
1963 1970 while len(h) == 20:
1964 1971 heads.append(h)
1965 1972 h = inpart.read(20)
1966 1973 assert not h
1967 1974 # trigger a transaction so that we are guaranteed to have the lock now.
1968 1975 if op.ui.configbool('experimental', 'bundle2lazylocking'):
1969 1976 op.gettransaction()
1970 1977
1971 1978 currentheads = set()
1972 1979 for ls in op.repo.branchmap().itervalues():
1973 1980 currentheads.update(ls)
1974 1981
1975 1982 for h in heads:
1976 1983 if h not in currentheads:
1977 1984 raise error.PushRaced('remote repository changed while pushing - '
1978 1985 'please try again')
1979 1986
1980 1987 @parthandler('check:phases')
1981 1988 def handlecheckphases(op, inpart):
1982 1989 """check that phase boundaries of the repository did not change
1983 1990
1984 1991 This is used to detect a push race.
1985 1992 """
1986 1993 phasetonodes = phases.binarydecode(inpart)
1987 1994 unfi = op.repo.unfiltered()
1988 1995 cl = unfi.changelog
1989 1996 phasecache = unfi._phasecache
1990 1997 msg = ('remote repository changed while pushing - please try again '
1991 1998 '(%s is %s expected %s)')
1992 1999 for expectedphase, nodes in enumerate(phasetonodes):
1993 2000 for n in nodes:
1994 2001 actualphase = phasecache.phase(unfi, cl.rev(n))
1995 2002 if actualphase != expectedphase:
1996 2003 finalmsg = msg % (nodemod.short(n),
1997 2004 phases.phasenames[actualphase],
1998 2005 phases.phasenames[expectedphase])
1999 2006 raise error.PushRaced(finalmsg)
2000 2007
2001 2008 @parthandler('output')
2002 2009 def handleoutput(op, inpart):
2003 2010 """forward output captured on the server to the client"""
2004 2011 for line in inpart.read().splitlines():
2005 2012 op.ui.status(_('remote: %s\n') % line)
2006 2013
2007 2014 @parthandler('replycaps')
2008 2015 def handlereplycaps(op, inpart):
2009 2016 """Notify that a reply bundle should be created
2010 2017
2011 2018 The payload contains the capabilities information for the reply"""
2012 2019 caps = decodecaps(inpart.read())
2013 2020 if op.reply is None:
2014 2021 op.reply = bundle20(op.ui, caps)
2015 2022
2016 2023 class AbortFromPart(error.Abort):
2017 2024 """Sub-class of Abort that denotes an error from a bundle2 part."""
2018 2025
2019 2026 @parthandler('error:abort', ('message', 'hint'))
2020 2027 def handleerrorabort(op, inpart):
2021 2028 """Used to transmit abort error over the wire"""
2022 2029 raise AbortFromPart(inpart.params['message'],
2023 2030 hint=inpart.params.get('hint'))
2024 2031
2025 2032 @parthandler('error:pushkey', ('namespace', 'key', 'new', 'old', 'ret',
2026 2033 'in-reply-to'))
2027 2034 def handleerrorpushkey(op, inpart):
2028 2035 """Used to transmit failure of a mandatory pushkey over the wire"""
2029 2036 kwargs = {}
2030 2037 for name in ('namespace', 'key', 'new', 'old', 'ret'):
2031 2038 value = inpart.params.get(name)
2032 2039 if value is not None:
2033 2040 kwargs[name] = value
2034 2041 raise error.PushkeyFailed(inpart.params['in-reply-to'],
2035 2042 **pycompat.strkwargs(kwargs))
2036 2043
2037 2044 @parthandler('error:unsupportedcontent', ('parttype', 'params'))
2038 2045 def handleerrorunsupportedcontent(op, inpart):
2039 2046 """Used to transmit unknown content error over the wire"""
2040 2047 kwargs = {}
2041 2048 parttype = inpart.params.get('parttype')
2042 2049 if parttype is not None:
2043 2050 kwargs['parttype'] = parttype
2044 2051 params = inpart.params.get('params')
2045 2052 if params is not None:
2046 2053 kwargs['params'] = params.split('\0')
2047 2054
2048 2055 raise error.BundleUnknownFeatureError(**pycompat.strkwargs(kwargs))
2049 2056
2050 2057 @parthandler('error:pushraced', ('message',))
2051 2058 def handleerrorpushraced(op, inpart):
2052 2059 """Used to transmit push race error over the wire"""
2053 2060 raise error.ResponseError(_('push failed:'), inpart.params['message'])
2054 2061
2055 2062 @parthandler('listkeys', ('namespace',))
2056 2063 def handlelistkeys(op, inpart):
2057 2064 """retrieve pushkey namespace content stored in a bundle2"""
2058 2065 namespace = inpart.params['namespace']
2059 2066 r = pushkey.decodekeys(inpart.read())
2060 2067 op.records.add('listkeys', (namespace, r))
2061 2068
2062 2069 @parthandler('pushkey', ('namespace', 'key', 'old', 'new'))
2063 2070 def handlepushkey(op, inpart):
2064 2071 """process a pushkey request"""
2065 2072 dec = pushkey.decode
2066 2073 namespace = dec(inpart.params['namespace'])
2067 2074 key = dec(inpart.params['key'])
2068 2075 old = dec(inpart.params['old'])
2069 2076 new = dec(inpart.params['new'])
2070 2077 # Grab the transaction to ensure that we have the lock before performing the
2071 2078 # pushkey.
2072 2079 if op.ui.configbool('experimental', 'bundle2lazylocking'):
2073 2080 op.gettransaction()
2074 2081 ret = op.repo.pushkey(namespace, key, old, new)
2075 2082 record = {'namespace': namespace,
2076 2083 'key': key,
2077 2084 'old': old,
2078 2085 'new': new}
2079 2086 op.records.add('pushkey', record)
2080 2087 if op.reply is not None:
2081 2088 rpart = op.reply.newpart('reply:pushkey')
2082 2089 rpart.addparam(
2083 2090 'in-reply-to', pycompat.bytestr(inpart.id), mandatory=False)
2084 2091 rpart.addparam('return', '%i' % ret, mandatory=False)
2085 2092 if inpart.mandatory and not ret:
2086 2093 kwargs = {}
2087 2094 for key in ('namespace', 'key', 'new', 'old', 'ret'):
2088 2095 if key in inpart.params:
2089 2096 kwargs[key] = inpart.params[key]
2090 2097 raise error.PushkeyFailed(partid='%d' % inpart.id,
2091 2098 **pycompat.strkwargs(kwargs))
2092 2099
2093 2100 @parthandler('bookmarks')
2094 2101 def handlebookmark(op, inpart):
2095 2102 """transmit bookmark information
2096 2103
2097 2104 The part contains binary encoded bookmark information.
2098 2105
2099 2106 The exact behavior of this part can be controlled by the 'bookmarks' mode
2100 2107 on the bundle operation.
2101 2108
2102 2109 When mode is 'apply' (the default) the bookmark information is applied as
2103 2110 is to the unbundling repository. Make sure a 'check:bookmarks' part is
2104 2111 issued earlier to check for push races in such update. This behavior is
2105 2112 suitable for pushing.
2106 2113
2107 2114 When mode is 'records', the information is recorded into the 'bookmarks'
2108 2115 records of the bundle operation. This behavior is suitable for pulling.
2109 2116 """
2110 2117 changes = bookmarks.binarydecode(inpart)
2111 2118
2112 2119 pushkeycompat = op.repo.ui.configbool('server', 'bookmarks-pushkey-compat')
2113 2120 bookmarksmode = op.modes.get('bookmarks', 'apply')
2114 2121
2115 2122 if bookmarksmode == 'apply':
2116 2123 tr = op.gettransaction()
2117 2124 bookstore = op.repo._bookmarks
2118 2125 if pushkeycompat:
2119 2126 allhooks = []
2120 2127 for book, node in changes:
2121 2128 hookargs = tr.hookargs.copy()
2122 2129 hookargs['pushkeycompat'] = '1'
2123 2130 hookargs['namespace'] = 'bookmarks'
2124 2131 hookargs['key'] = book
2125 2132 hookargs['old'] = nodemod.hex(bookstore.get(book, ''))
2126 2133 hookargs['new'] = nodemod.hex(node if node is not None else '')
2127 2134 allhooks.append(hookargs)
2128 2135
2129 2136 for hookargs in allhooks:
2130 2137 op.repo.hook('prepushkey', throw=True,
2131 2138 **pycompat.strkwargs(hookargs))
2132 2139
2133 2140 bookstore.applychanges(op.repo, op.gettransaction(), changes)
2134 2141
2135 2142 if pushkeycompat:
2136 2143 def runhook():
2137 2144 for hookargs in allhooks:
2138 2145 op.repo.hook('pushkey', **pycompat.strkwargs(hookargs))
2139 2146 op.repo._afterlock(runhook)
2140 2147
2141 2148 elif bookmarksmode == 'records':
2142 2149 for book, node in changes:
2143 2150 record = {'bookmark': book, 'node': node}
2144 2151 op.records.add('bookmarks', record)
2145 2152 else:
2146 2153 raise error.ProgrammingError('unkown bookmark mode: %s' % bookmarksmode)
2147 2154
2148 2155 @parthandler('phase-heads')
2149 2156 def handlephases(op, inpart):
2150 2157 """apply phases from bundle part to repo"""
2151 2158 headsbyphase = phases.binarydecode(inpart)
2152 2159 phases.updatephases(op.repo.unfiltered(), op.gettransaction, headsbyphase)
2153 2160
2154 2161 @parthandler('reply:pushkey', ('return', 'in-reply-to'))
2155 2162 def handlepushkeyreply(op, inpart):
2156 2163 """retrieve the result of a pushkey request"""
2157 2164 ret = int(inpart.params['return'])
2158 2165 partid = int(inpart.params['in-reply-to'])
2159 2166 op.records.add('pushkey', {'return': ret}, partid)
2160 2167
2161 2168 @parthandler('obsmarkers')
2162 2169 def handleobsmarker(op, inpart):
2163 2170 """add a stream of obsmarkers to the repo"""
2164 2171 tr = op.gettransaction()
2165 2172 markerdata = inpart.read()
2166 2173 if op.ui.config('experimental', 'obsmarkers-exchange-debug'):
2167 2174 op.ui.write(('obsmarker-exchange: %i bytes received\n')
2168 2175 % len(markerdata))
2169 2176 # The mergemarkers call will crash if marker creation is not enabled.
2170 2177 # we want to avoid this if the part is advisory.
2171 2178 if not inpart.mandatory and op.repo.obsstore.readonly:
2172 2179 op.repo.ui.debug('ignoring obsolescence markers, feature not enabled\n')
2173 2180 return
2174 2181 new = op.repo.obsstore.mergemarkers(tr, markerdata)
2175 2182 op.repo.invalidatevolatilesets()
2176 2183 if new:
2177 2184 op.repo.ui.status(_('%i new obsolescence markers\n') % new)
2178 2185 op.records.add('obsmarkers', {'new': new})
2179 2186 if op.reply is not None:
2180 2187 rpart = op.reply.newpart('reply:obsmarkers')
2181 2188 rpart.addparam(
2182 2189 'in-reply-to', pycompat.bytestr(inpart.id), mandatory=False)
2183 2190 rpart.addparam('new', '%i' % new, mandatory=False)
2184 2191
2185 2192
2186 2193 @parthandler('reply:obsmarkers', ('new', 'in-reply-to'))
2187 2194 def handleobsmarkerreply(op, inpart):
2188 2195 """retrieve the result of a pushkey request"""
2189 2196 ret = int(inpart.params['new'])
2190 2197 partid = int(inpart.params['in-reply-to'])
2191 2198 op.records.add('obsmarkers', {'new': ret}, partid)
2192 2199
2193 2200 @parthandler('hgtagsfnodes')
2194 2201 def handlehgtagsfnodes(op, inpart):
2195 2202 """Applies .hgtags fnodes cache entries to the local repo.
2196 2203
2197 2204 Payload is pairs of 20 byte changeset nodes and filenodes.
2198 2205 """
2199 2206 # Grab the transaction so we ensure that we have the lock at this point.
2200 2207 if op.ui.configbool('experimental', 'bundle2lazylocking'):
2201 2208 op.gettransaction()
2202 2209 cache = tags.hgtagsfnodescache(op.repo.unfiltered())
2203 2210
2204 2211 count = 0
2205 2212 while True:
2206 2213 node = inpart.read(20)
2207 2214 fnode = inpart.read(20)
2208 2215 if len(node) < 20 or len(fnode) < 20:
2209 2216 op.ui.debug('ignoring incomplete received .hgtags fnodes data\n')
2210 2217 break
2211 2218 cache.setfnode(node, fnode)
2212 2219 count += 1
2213 2220
2214 2221 cache.write()
2215 2222 op.ui.debug('applied %i hgtags fnodes cache entries\n' % count)
2216 2223
2217 2224 rbcstruct = struct.Struct('>III')
2218 2225
2219 2226 @parthandler('cache:rev-branch-cache')
2220 2227 def handlerbc(op, inpart):
2221 2228 """receive a rev-branch-cache payload and update the local cache
2222 2229
2223 2230 The payload is a series of data related to each branch
2224 2231
2225 2232 1) branch name length
2226 2233 2) number of open heads
2227 2234 3) number of closed heads
2228 2235 4) open heads nodes
2229 2236 5) closed heads nodes
2230 2237 """
2231 2238 total = 0
2232 2239 rawheader = inpart.read(rbcstruct.size)
2233 2240 cache = op.repo.revbranchcache()
2234 2241 cl = op.repo.unfiltered().changelog
2235 2242 while rawheader:
2236 2243 header = rbcstruct.unpack(rawheader)
2237 2244 total += header[1] + header[2]
2238 2245 utf8branch = inpart.read(header[0])
2239 2246 branch = encoding.tolocal(utf8branch)
2240 2247 for x in pycompat.xrange(header[1]):
2241 2248 node = inpart.read(20)
2242 2249 rev = cl.rev(node)
2243 2250 cache.setdata(branch, rev, node, False)
2244 2251 for x in pycompat.xrange(header[2]):
2245 2252 node = inpart.read(20)
2246 2253 rev = cl.rev(node)
2247 2254 cache.setdata(branch, rev, node, True)
2248 2255 rawheader = inpart.read(rbcstruct.size)
2249 2256 cache.write()
2250 2257
2251 2258 @parthandler('pushvars')
2252 2259 def bundle2getvars(op, part):
2253 2260 '''unbundle a bundle2 containing shellvars on the server'''
2254 2261 # An option to disable unbundling on server-side for security reasons
2255 2262 if op.ui.configbool('push', 'pushvars.server'):
2256 2263 hookargs = {}
2257 2264 for key, value in part.advisoryparams:
2258 2265 key = key.upper()
2259 2266 # We want pushed variables to have USERVAR_ prepended so we know
2260 2267 # they came from the --pushvar flag.
2261 2268 key = "USERVAR_" + key
2262 2269 hookargs[key] = value
2263 2270 op.addhookargs(hookargs)
2264 2271
2265 2272 @parthandler('stream2', ('requirements', 'filecount', 'bytecount'))
2266 2273 def handlestreamv2bundle(op, part):
2267 2274
2268 2275 requirements = urlreq.unquote(part.params['requirements']).split(',')
2269 2276 filecount = int(part.params['filecount'])
2270 2277 bytecount = int(part.params['bytecount'])
2271 2278
2272 2279 repo = op.repo
2273 2280 if len(repo):
2274 2281 msg = _('cannot apply stream clone to non empty repository')
2275 2282 raise error.Abort(msg)
2276 2283
2277 2284 repo.ui.debug('applying stream bundle\n')
2278 2285 streamclone.applybundlev2(repo, part, filecount, bytecount,
2279 2286 requirements)
2280 2287
2281 2288 def widen_bundle(repo, oldmatcher, newmatcher, common, known, cgversion,
2282 2289 ellipses):
2283 2290 """generates bundle2 for widening a narrow clone
2284 2291
2285 2292 repo is the localrepository instance
2286 2293 oldmatcher matches what the client already has
2287 2294 newmatcher matches what the client needs (including what it already has)
2288 2295 common is set of common heads between server and client
2289 2296 known is a set of revs known on the client side (used in ellipses)
2290 2297 cgversion is the changegroup version to send
2291 2298 ellipses is boolean value telling whether to send ellipses data or not
2292 2299
2293 2300 returns bundle2 of the data required for extending
2294 2301 """
2295 2302 bundler = bundle20(repo.ui)
2296 2303 commonnodes = set()
2297 2304 cl = repo.changelog
2298 2305 for r in repo.revs("::%ln", common):
2299 2306 commonnodes.add(cl.node(r))
2300 2307 if commonnodes:
2301 2308 # XXX: we should only send the filelogs (and treemanifest). user
2302 2309 # already has the changelog and manifest
2303 2310 packer = changegroup.getbundler(cgversion, repo,
2304 2311 oldmatcher=oldmatcher,
2305 2312 matcher=newmatcher,
2306 2313 fullnodes=commonnodes)
2307 2314 cgdata = packer.generate(set([nodemod.nullid]), list(commonnodes),
2308 2315 False, 'narrow_widen', changelog=False)
2309 2316
2310 2317 part = bundler.newpart('changegroup', data=cgdata)
2311 2318 part.addparam('version', cgversion)
2312 2319 if 'treemanifest' in repo.requirements:
2313 2320 part.addparam('treemanifest', '1')
2314 2321
2315 2322 return bundler
@@ -1,660 +1,663 b''
1 1 # streamclone.py - producing and consuming streaming repository data
2 2 #
3 3 # Copyright 2015 Gregory Szorc <gregory.szorc@gmail.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 from __future__ import absolute_import
9 9
10 10 import contextlib
11 11 import os
12 12 import struct
13 13
14 14 from .i18n import _
15 15 from . import (
16 16 branchmap,
17 17 cacheutil,
18 18 error,
19 19 narrowspec,
20 20 phases,
21 21 pycompat,
22 22 repository,
23 23 store,
24 24 util,
25 25 )
26 26
27 27 def canperformstreamclone(pullop, bundle2=False):
28 28 """Whether it is possible to perform a streaming clone as part of pull.
29 29
30 30 ``bundle2`` will cause the function to consider stream clone through
31 31 bundle2 and only through bundle2.
32 32
33 33 Returns a tuple of (supported, requirements). ``supported`` is True if
34 34 streaming clone is supported and False otherwise. ``requirements`` is
35 35 a set of repo requirements from the remote, or ``None`` if stream clone
36 36 isn't supported.
37 37 """
38 38 repo = pullop.repo
39 39 remote = pullop.remote
40 40
41 41 bundle2supported = False
42 42 if pullop.canusebundle2:
43 43 if 'v2' in pullop.remotebundle2caps.get('stream', []):
44 44 bundle2supported = True
45 45 # else
46 46 # Server doesn't support bundle2 stream clone or doesn't support
47 47 # the versions we support. Fall back and possibly allow legacy.
48 48
49 49 # Ensures legacy code path uses available bundle2.
50 50 if bundle2supported and not bundle2:
51 51 return False, None
52 52 # Ensures bundle2 doesn't try to do a stream clone if it isn't supported.
53 53 elif bundle2 and not bundle2supported:
54 54 return False, None
55 55
56 56 # Streaming clone only works on empty repositories.
57 57 if len(repo):
58 58 return False, None
59 59
60 60 # Streaming clone only works if all data is being requested.
61 61 if pullop.heads:
62 62 return False, None
63 63
64 64 streamrequested = pullop.streamclonerequested
65 65
66 66 # If we don't have a preference, let the server decide for us. This
67 67 # likely only comes into play in LANs.
68 68 if streamrequested is None:
69 69 # The server can advertise whether to prefer streaming clone.
70 70 streamrequested = remote.capable('stream-preferred')
71 71
72 72 if not streamrequested:
73 73 return False, None
74 74
75 75 # In order for stream clone to work, the client has to support all the
76 76 # requirements advertised by the server.
77 77 #
78 78 # The server advertises its requirements via the "stream" and "streamreqs"
79 79 # capability. "stream" (a value-less capability) is advertised if and only
80 80 # if the only requirement is "revlogv1." Else, the "streamreqs" capability
81 81 # is advertised and contains a comma-delimited list of requirements.
82 82 requirements = set()
83 83 if remote.capable('stream'):
84 84 requirements.add('revlogv1')
85 85 else:
86 86 streamreqs = remote.capable('streamreqs')
87 87 # This is weird and shouldn't happen with modern servers.
88 88 if not streamreqs:
89 89 pullop.repo.ui.warn(_(
90 90 'warning: stream clone requested but server has them '
91 91 'disabled\n'))
92 92 return False, None
93 93
94 94 streamreqs = set(streamreqs.split(','))
95 95 # Server requires something we don't support. Bail.
96 96 missingreqs = streamreqs - repo.supportedformats
97 97 if missingreqs:
98 98 pullop.repo.ui.warn(_(
99 99 'warning: stream clone requested but client is missing '
100 100 'requirements: %s\n') % ', '.join(sorted(missingreqs)))
101 101 pullop.repo.ui.warn(
102 102 _('(see https://www.mercurial-scm.org/wiki/MissingRequirement '
103 103 'for more information)\n'))
104 104 return False, None
105 105 requirements = streamreqs
106 106
107 107 return True, requirements
108 108
109 109 def maybeperformlegacystreamclone(pullop):
110 110 """Possibly perform a legacy stream clone operation.
111 111
112 112 Legacy stream clones are performed as part of pull but before all other
113 113 operations.
114 114
115 115 A legacy stream clone will not be performed if a bundle2 stream clone is
116 116 supported.
117 117 """
118 118 from . import localrepo
119 119
120 120 supported, requirements = canperformstreamclone(pullop)
121 121
122 122 if not supported:
123 123 return
124 124
125 125 repo = pullop.repo
126 126 remote = pullop.remote
127 127
128 128 # Save remote branchmap. We will use it later to speed up branchcache
129 129 # creation.
130 130 rbranchmap = None
131 131 if remote.capable('branchmap'):
132 132 with remote.commandexecutor() as e:
133 133 rbranchmap = e.callcommand('branchmap', {}).result()
134 134
135 135 repo.ui.status(_('streaming all changes\n'))
136 136
137 137 with remote.commandexecutor() as e:
138 138 fp = e.callcommand('stream_out', {}).result()
139 139
140 140 # TODO strictly speaking, this code should all be inside the context
141 141 # manager because the context manager is supposed to ensure all wire state
142 142 # is flushed when exiting. But the legacy peers don't do this, so it
143 143 # doesn't matter.
144 144 l = fp.readline()
145 145 try:
146 146 resp = int(l)
147 147 except ValueError:
148 148 raise error.ResponseError(
149 149 _('unexpected response from remote server:'), l)
150 150 if resp == 1:
151 151 raise error.Abort(_('operation forbidden by server'))
152 152 elif resp == 2:
153 153 raise error.Abort(_('locking the remote repository failed'))
154 154 elif resp != 0:
155 155 raise error.Abort(_('the server sent an unknown error code'))
156 156
157 157 l = fp.readline()
158 158 try:
159 159 filecount, bytecount = map(int, l.split(' ', 1))
160 160 except (ValueError, TypeError):
161 161 raise error.ResponseError(
162 162 _('unexpected response from remote server:'), l)
163 163
164 164 with repo.lock():
165 165 consumev1(repo, fp, filecount, bytecount)
166 166
167 167 # new requirements = old non-format requirements +
168 168 # new format-related remote requirements
169 169 # requirements from the streamed-in repository
170 170 repo.requirements = requirements | (
171 171 repo.requirements - repo.supportedformats)
172 172 repo.svfs.options = localrepo.resolvestorevfsoptions(
173 173 repo.ui, repo.requirements, repo.features)
174 174 repo._writerequirements()
175 175
176 176 if rbranchmap:
177 177 branchmap.replacecache(repo, rbranchmap)
178 178
179 179 repo.invalidate()
180 180
181 181 def allowservergeneration(repo):
182 182 """Whether streaming clones are allowed from the server."""
183 183 if repository.REPO_FEATURE_STREAM_CLONE not in repo.features:
184 184 return False
185 185
186 186 if not repo.ui.configbool('server', 'uncompressed', untrusted=True):
187 187 return False
188 188
189 189 # The way stream clone works makes it impossible to hide secret changesets.
190 190 # So don't allow this by default.
191 191 secret = phases.hassecret(repo)
192 192 if secret:
193 193 return repo.ui.configbool('server', 'uncompressedallowsecret')
194 194
195 195 return True
196 196
197 197 # This is it's own function so extensions can override it.
198 198 def _walkstreamfiles(repo, matcher=None):
199 199 return repo.store.walk(matcher)
200 200
201 201 def generatev1(repo):
202 202 """Emit content for version 1 of a streaming clone.
203 203
204 204 This returns a 3-tuple of (file count, byte size, data iterator).
205 205
206 206 The data iterator consists of N entries for each file being transferred.
207 207 Each file entry starts as a line with the file name and integer size
208 208 delimited by a null byte.
209 209
210 210 The raw file data follows. Following the raw file data is the next file
211 211 entry, or EOF.
212 212
213 213 When used on the wire protocol, an additional line indicating protocol
214 214 success will be prepended to the stream. This function is not responsible
215 215 for adding it.
216 216
217 217 This function will obtain a repository lock to ensure a consistent view of
218 218 the store is captured. It therefore may raise LockError.
219 219 """
220 220 entries = []
221 221 total_bytes = 0
222 222 # Get consistent snapshot of repo, lock during scan.
223 223 with repo.lock():
224 224 repo.ui.debug('scanning\n')
225 225 for name, ename, size in _walkstreamfiles(repo):
226 226 if size:
227 227 entries.append((name, size))
228 228 total_bytes += size
229 229
230 230 repo.ui.debug('%d files, %d bytes to transfer\n' %
231 231 (len(entries), total_bytes))
232 232
233 233 svfs = repo.svfs
234 234 debugflag = repo.ui.debugflag
235 235
236 236 def emitrevlogdata():
237 237 for name, size in entries:
238 238 if debugflag:
239 239 repo.ui.debug('sending %s (%d bytes)\n' % (name, size))
240 240 # partially encode name over the wire for backwards compat
241 241 yield '%s\0%d\n' % (store.encodedir(name), size)
242 242 # auditing at this stage is both pointless (paths are already
243 243 # trusted by the local repo) and expensive
244 244 with svfs(name, 'rb', auditpath=False) as fp:
245 245 if size <= 65536:
246 246 yield fp.read(size)
247 247 else:
248 248 for chunk in util.filechunkiter(fp, limit=size):
249 249 yield chunk
250 250
251 251 return len(entries), total_bytes, emitrevlogdata()
252 252
253 253 def generatev1wireproto(repo):
254 254 """Emit content for version 1 of streaming clone suitable for the wire.
255 255
256 256 This is the data output from ``generatev1()`` with 2 header lines. The
257 257 first line indicates overall success. The 2nd contains the file count and
258 258 byte size of payload.
259 259
260 260 The success line contains "0" for success, "1" for stream generation not
261 261 allowed, and "2" for error locking the repository (possibly indicating
262 262 a permissions error for the server process).
263 263 """
264 264 if not allowservergeneration(repo):
265 265 yield '1\n'
266 266 return
267 267
268 268 try:
269 269 filecount, bytecount, it = generatev1(repo)
270 270 except error.LockError:
271 271 yield '2\n'
272 272 return
273 273
274 274 # Indicates successful response.
275 275 yield '0\n'
276 276 yield '%d %d\n' % (filecount, bytecount)
277 277 for chunk in it:
278 278 yield chunk
279 279
280 280 def generatebundlev1(repo, compression='UN'):
281 281 """Emit content for version 1 of a stream clone bundle.
282 282
283 283 The first 4 bytes of the output ("HGS1") denote this as stream clone
284 284 bundle version 1.
285 285
286 286 The next 2 bytes indicate the compression type. Only "UN" is currently
287 287 supported.
288 288
289 289 The next 16 bytes are two 64-bit big endian unsigned integers indicating
290 290 file count and byte count, respectively.
291 291
292 292 The next 2 bytes is a 16-bit big endian unsigned short declaring the length
293 293 of the requirements string, including a trailing \0. The following N bytes
294 294 are the requirements string, which is ASCII containing a comma-delimited
295 295 list of repo requirements that are needed to support the data.
296 296
297 297 The remaining content is the output of ``generatev1()`` (which may be
298 298 compressed in the future).
299 299
300 300 Returns a tuple of (requirements, data generator).
301 301 """
302 302 if compression != 'UN':
303 303 raise ValueError('we do not support the compression argument yet')
304 304
305 305 requirements = repo.requirements & repo.supportedformats
306 306 requires = ','.join(sorted(requirements))
307 307
308 308 def gen():
309 309 yield 'HGS1'
310 310 yield compression
311 311
312 312 filecount, bytecount, it = generatev1(repo)
313 313 repo.ui.status(_('writing %d bytes for %d files\n') %
314 314 (bytecount, filecount))
315 315
316 316 yield struct.pack('>QQ', filecount, bytecount)
317 317 yield struct.pack('>H', len(requires) + 1)
318 318 yield requires + '\0'
319 319
320 320 # This is where we'll add compression in the future.
321 321 assert compression == 'UN'
322 322
323 323 progress = repo.ui.makeprogress(_('bundle'), total=bytecount,
324 324 unit=_('bytes'))
325 325 progress.update(0)
326 326
327 327 for chunk in it:
328 328 progress.increment(step=len(chunk))
329 329 yield chunk
330 330
331 331 progress.complete()
332 332
333 333 return requirements, gen()
334 334
335 335 def consumev1(repo, fp, filecount, bytecount):
336 336 """Apply the contents from version 1 of a streaming clone file handle.
337 337
338 338 This takes the output from "stream_out" and applies it to the specified
339 339 repository.
340 340
341 341 Like "stream_out," the status line added by the wire protocol is not
342 342 handled by this function.
343 343 """
344 344 with repo.lock():
345 345 repo.ui.status(_('%d files to transfer, %s of data\n') %
346 346 (filecount, util.bytecount(bytecount)))
347 347 progress = repo.ui.makeprogress(_('clone'), total=bytecount,
348 348 unit=_('bytes'))
349 349 progress.update(0)
350 350 start = util.timer()
351 351
352 352 # TODO: get rid of (potential) inconsistency
353 353 #
354 354 # If transaction is started and any @filecache property is
355 355 # changed at this point, it causes inconsistency between
356 356 # in-memory cached property and streamclone-ed file on the
357 357 # disk. Nested transaction prevents transaction scope "clone"
358 358 # below from writing in-memory changes out at the end of it,
359 359 # even though in-memory changes are discarded at the end of it
360 360 # regardless of transaction nesting.
361 361 #
362 362 # But transaction nesting can't be simply prohibited, because
363 363 # nesting occurs also in ordinary case (e.g. enabling
364 364 # clonebundles).
365 365
366 366 with repo.transaction('clone'):
367 367 with repo.svfs.backgroundclosing(repo.ui, expectedcount=filecount):
368 368 for i in pycompat.xrange(filecount):
369 369 # XXX doesn't support '\n' or '\r' in filenames
370 370 l = fp.readline()
371 371 try:
372 372 name, size = l.split('\0', 1)
373 373 size = int(size)
374 374 except (ValueError, TypeError):
375 375 raise error.ResponseError(
376 376 _('unexpected response from remote server:'), l)
377 377 if repo.ui.debugflag:
378 378 repo.ui.debug('adding %s (%s)\n' %
379 379 (name, util.bytecount(size)))
380 380 # for backwards compat, name was partially encoded
381 381 path = store.decodedir(name)
382 382 with repo.svfs(path, 'w', backgroundclose=True) as ofp:
383 383 for chunk in util.filechunkiter(fp, limit=size):
384 384 progress.increment(step=len(chunk))
385 385 ofp.write(chunk)
386 386
387 387 # force @filecache properties to be reloaded from
388 388 # streamclone-ed file at next access
389 389 repo.invalidate(clearfilecache=True)
390 390
391 391 elapsed = util.timer() - start
392 392 if elapsed <= 0:
393 393 elapsed = 0.001
394 394 progress.complete()
395 395 repo.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
396 396 (util.bytecount(bytecount), elapsed,
397 397 util.bytecount(bytecount / elapsed)))
398 398
399 399 def readbundle1header(fp):
400 400 compression = fp.read(2)
401 401 if compression != 'UN':
402 402 raise error.Abort(_('only uncompressed stream clone bundles are '
403 403 'supported; got %s') % compression)
404 404
405 405 filecount, bytecount = struct.unpack('>QQ', fp.read(16))
406 406 requireslen = struct.unpack('>H', fp.read(2))[0]
407 407 requires = fp.read(requireslen)
408 408
409 409 if not requires.endswith('\0'):
410 410 raise error.Abort(_('malformed stream clone bundle: '
411 411 'requirements not properly encoded'))
412 412
413 413 requirements = set(requires.rstrip('\0').split(','))
414 414
415 415 return filecount, bytecount, requirements
416 416
417 417 def applybundlev1(repo, fp):
418 418 """Apply the content from a stream clone bundle version 1.
419 419
420 420 We assume the 4 byte header has been read and validated and the file handle
421 421 is at the 2 byte compression identifier.
422 422 """
423 423 if len(repo):
424 424 raise error.Abort(_('cannot apply stream clone bundle on non-empty '
425 425 'repo'))
426 426
427 427 filecount, bytecount, requirements = readbundle1header(fp)
428 428 missingreqs = requirements - repo.supportedformats
429 429 if missingreqs:
430 430 raise error.Abort(_('unable to apply stream clone: '
431 431 'unsupported format: %s') %
432 432 ', '.join(sorted(missingreqs)))
433 433
434 434 consumev1(repo, fp, filecount, bytecount)
435 435
436 436 class streamcloneapplier(object):
437 437 """Class to manage applying streaming clone bundles.
438 438
439 439 We need to wrap ``applybundlev1()`` in a dedicated type to enable bundle
440 440 readers to perform bundle type-specific functionality.
441 441 """
442 442 def __init__(self, fh):
443 443 self._fh = fh
444 444
445 445 def apply(self, repo):
446 446 return applybundlev1(repo, self._fh)
447 447
448 448 # type of file to stream
449 449 _fileappend = 0 # append only file
450 450 _filefull = 1 # full snapshot file
451 451
452 452 # Source of the file
453 453 _srcstore = 's' # store (svfs)
454 454 _srccache = 'c' # cache (cache)
455 455
456 456 # This is it's own function so extensions can override it.
457 457 def _walkstreamfullstorefiles(repo):
458 458 """list snapshot file from the store"""
459 459 fnames = []
460 460 if not repo.publishing():
461 461 fnames.append('phaseroots')
462 462 return fnames
463 463
464 464 def _filterfull(entry, copy, vfsmap):
465 465 """actually copy the snapshot files"""
466 466 src, name, ftype, data = entry
467 467 if ftype != _filefull:
468 468 return entry
469 469 return (src, name, ftype, copy(vfsmap[src].join(name)))
470 470
471 471 @contextlib.contextmanager
472 472 def maketempcopies():
473 473 """return a function to temporary copy file"""
474 474 files = []
475 475 try:
476 476 def copy(src):
477 477 fd, dst = pycompat.mkstemp()
478 478 os.close(fd)
479 479 files.append(dst)
480 480 util.copyfiles(src, dst, hardlink=True)
481 481 return dst
482 482 yield copy
483 483 finally:
484 484 for tmp in files:
485 485 util.tryunlink(tmp)
486 486
487 487 def _makemap(repo):
488 488 """make a (src -> vfs) map for the repo"""
489 489 vfsmap = {
490 490 _srcstore: repo.svfs,
491 491 _srccache: repo.cachevfs,
492 492 }
493 493 # we keep repo.vfs out of the on purpose, ther are too many danger there
494 494 # (eg: .hg/hgrc)
495 495 assert repo.vfs not in vfsmap.values()
496 496
497 497 return vfsmap
498 498
499 499 def _emit2(repo, entries, totalfilesize):
500 500 """actually emit the stream bundle"""
501 501 vfsmap = _makemap(repo)
502 502 progress = repo.ui.makeprogress(_('bundle'), total=totalfilesize,
503 503 unit=_('bytes'))
504 504 progress.update(0)
505 505 with maketempcopies() as copy, progress:
506 506 # copy is delayed until we are in the try
507 507 entries = [_filterfull(e, copy, vfsmap) for e in entries]
508 508 yield None # this release the lock on the repository
509 509 seen = 0
510 510
511 511 for src, name, ftype, data in entries:
512 512 vfs = vfsmap[src]
513 513 yield src
514 514 yield util.uvarintencode(len(name))
515 515 if ftype == _fileappend:
516 516 fp = vfs(name)
517 517 size = data
518 518 elif ftype == _filefull:
519 519 fp = open(data, 'rb')
520 520 size = util.fstat(fp).st_size
521 521 try:
522 522 yield util.uvarintencode(size)
523 523 yield name
524 524 if size <= 65536:
525 525 chunks = (fp.read(size),)
526 526 else:
527 527 chunks = util.filechunkiter(fp, limit=size)
528 528 for chunk in chunks:
529 529 seen += len(chunk)
530 530 progress.update(seen)
531 531 yield chunk
532 532 finally:
533 533 fp.close()
534 534
535 def generatev2(repo, includes, excludes):
535 def generatev2(repo, includes, excludes, includeobsmarkers):
536 536 """Emit content for version 2 of a streaming clone.
537 537
538 538 the data stream consists the following entries:
539 539 1) A char representing the file destination (eg: store or cache)
540 540 2) A varint containing the length of the filename
541 541 3) A varint containing the length of file data
542 542 4) N bytes containing the filename (the internal, store-agnostic form)
543 543 5) N bytes containing the file data
544 544
545 545 Returns a 3-tuple of (file count, file size, data iterator).
546 546 """
547 547
548 548 # temporarily raise error until we add storage level logic
549 549 if includes or excludes:
550 550 raise error.Abort(_("server does not support narrow stream clones"))
551 551
552 552 with repo.lock():
553 553
554 554 entries = []
555 555 totalfilesize = 0
556 556
557 557 matcher = None
558 558 if includes or excludes:
559 559 matcher = narrowspec.match(repo.root, includes, excludes)
560 560
561 561 repo.ui.debug('scanning\n')
562 562 for name, ename, size in _walkstreamfiles(repo, matcher):
563 563 if size:
564 564 entries.append((_srcstore, name, _fileappend, size))
565 565 totalfilesize += size
566 566 for name in _walkstreamfullstorefiles(repo):
567 567 if repo.svfs.exists(name):
568 568 totalfilesize += repo.svfs.lstat(name).st_size
569 569 entries.append((_srcstore, name, _filefull, None))
570 if includeobsmarkers and repo.svfs.exists('obsstore'):
571 totalfilesize += repo.svfs.lstat('obsstore').st_size
572 entries.append((_srcstore, 'obsstore', _filefull, None))
570 573 for name in cacheutil.cachetocopy(repo):
571 574 if repo.cachevfs.exists(name):
572 575 totalfilesize += repo.cachevfs.lstat(name).st_size
573 576 entries.append((_srccache, name, _filefull, None))
574 577
575 578 chunks = _emit2(repo, entries, totalfilesize)
576 579 first = next(chunks)
577 580 assert first is None
578 581
579 582 return len(entries), totalfilesize, chunks
580 583
581 584 @contextlib.contextmanager
582 585 def nested(*ctxs):
583 586 this = ctxs[0]
584 587 rest = ctxs[1:]
585 588 with this:
586 589 if rest:
587 590 with nested(*rest):
588 591 yield
589 592 else:
590 593 yield
591 594
592 595 def consumev2(repo, fp, filecount, filesize):
593 596 """Apply the contents from a version 2 streaming clone.
594 597
595 598 Data is read from an object that only needs to provide a ``read(size)``
596 599 method.
597 600 """
598 601 with repo.lock():
599 602 repo.ui.status(_('%d files to transfer, %s of data\n') %
600 603 (filecount, util.bytecount(filesize)))
601 604
602 605 start = util.timer()
603 606 progress = repo.ui.makeprogress(_('clone'), total=filesize,
604 607 unit=_('bytes'))
605 608 progress.update(0)
606 609
607 610 vfsmap = _makemap(repo)
608 611
609 612 with repo.transaction('clone'):
610 613 ctxs = (vfs.backgroundclosing(repo.ui)
611 614 for vfs in vfsmap.values())
612 615 with nested(*ctxs):
613 616 for i in range(filecount):
614 617 src = util.readexactly(fp, 1)
615 618 vfs = vfsmap[src]
616 619 namelen = util.uvarintdecodestream(fp)
617 620 datalen = util.uvarintdecodestream(fp)
618 621
619 622 name = util.readexactly(fp, namelen)
620 623
621 624 if repo.ui.debugflag:
622 625 repo.ui.debug('adding [%s] %s (%s)\n' %
623 626 (src, name, util.bytecount(datalen)))
624 627
625 628 with vfs(name, 'w') as ofp:
626 629 for chunk in util.filechunkiter(fp, limit=datalen):
627 630 progress.increment(step=len(chunk))
628 631 ofp.write(chunk)
629 632
630 633 # force @filecache properties to be reloaded from
631 634 # streamclone-ed file at next access
632 635 repo.invalidate(clearfilecache=True)
633 636
634 637 elapsed = util.timer() - start
635 638 if elapsed <= 0:
636 639 elapsed = 0.001
637 640 repo.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
638 641 (util.bytecount(progress.pos), elapsed,
639 642 util.bytecount(progress.pos / elapsed)))
640 643 progress.complete()
641 644
642 645 def applybundlev2(repo, fp, filecount, filesize, requirements):
643 646 from . import localrepo
644 647
645 648 missingreqs = [r for r in requirements if r not in repo.supported]
646 649 if missingreqs:
647 650 raise error.Abort(_('unable to apply stream clone: '
648 651 'unsupported format: %s') %
649 652 ', '.join(sorted(missingreqs)))
650 653
651 654 consumev2(repo, fp, filecount, filesize)
652 655
653 656 # new requirements = old non-format requirements +
654 657 # new format-related remote requirements
655 658 # requirements from the streamed-in repository
656 659 repo.requirements = set(requirements) | (
657 660 repo.requirements - repo.supportedformats)
658 661 repo.svfs.options = localrepo.resolvestorevfsoptions(
659 662 repo.ui, repo.requirements, repo.features)
660 663 repo._writerequirements()
@@ -1,516 +1,561 b''
1 1 #require serve no-reposimplestore no-chg
2 2
3 3 #testcases stream-legacy stream-bundle2
4 4
5 5 #if stream-legacy
6 6 $ cat << EOF >> $HGRCPATH
7 7 > [server]
8 8 > bundle2.stream = no
9 9 > EOF
10 10 #endif
11 11
12 12 Initialize repository
13 13 the status call is to check for issue5130
14 14
15 15 $ hg init server
16 16 $ cd server
17 17 $ touch foo
18 18 $ hg -q commit -A -m initial
19 19 >>> for i in range(1024):
20 20 ... with open(str(i), 'wb') as fh:
21 21 ... fh.write(b"%d" % i) and None
22 22 $ hg -q commit -A -m 'add a lot of files'
23 23 $ hg st
24 24 $ hg --config server.uncompressed=false serve -p $HGPORT -d --pid-file=hg.pid
25 25 $ cat hg.pid > $DAEMON_PIDS
26 26 $ cd ..
27 27
28 28 Cannot stream clone when server.uncompressed is set
29 29
30 30 $ get-with-headers.py $LOCALIP:$HGPORT '?cmd=stream_out'
31 31 200 Script output follows
32 32
33 33 1
34 34
35 35 #if stream-legacy
36 36 $ hg debugcapabilities http://localhost:$HGPORT
37 37 Main capabilities:
38 38 batch
39 39 branchmap
40 40 $USUAL_BUNDLE2_CAPS_SERVER$
41 41 changegroupsubset
42 42 compression=$BUNDLE2_COMPRESSIONS$
43 43 getbundle
44 44 httpheader=1024
45 45 httpmediatype=0.1rx,0.1tx,0.2tx
46 46 known
47 47 lookup
48 48 pushkey
49 49 unbundle=HG10GZ,HG10BZ,HG10UN
50 50 unbundlehash
51 51 Bundle2 capabilities:
52 52 HG20
53 53 bookmarks
54 54 changegroup
55 55 01
56 56 02
57 57 digests
58 58 md5
59 59 sha1
60 60 sha512
61 61 error
62 62 abort
63 63 unsupportedcontent
64 64 pushraced
65 65 pushkey
66 66 hgtagsfnodes
67 67 listkeys
68 68 phases
69 69 heads
70 70 pushkey
71 71 remote-changegroup
72 72 http
73 73 https
74 74 rev-branch-cache
75 75
76 76 $ hg clone --stream -U http://localhost:$HGPORT server-disabled
77 77 warning: stream clone requested but server has them disabled
78 78 requesting all changes
79 79 adding changesets
80 80 adding manifests
81 81 adding file changes
82 82 added 2 changesets with 1025 changes to 1025 files
83 83 new changesets 96ee1d7354c4:c17445101a72
84 84
85 85 $ get-with-headers.py $LOCALIP:$HGPORT '?cmd=getbundle' content-type --bodyfile body --hgproto 0.2 --requestheader "x-hgarg-1=bundlecaps=HG20%2Cbundle2%3DHG20%250Abookmarks%250Achangegroup%253D01%252C02%250Adigests%253Dmd5%252Csha1%252Csha512%250Aerror%253Dabort%252Cunsupportedcontent%252Cpushraced%252Cpushkey%250Ahgtagsfnodes%250Alistkeys%250Aphases%253Dheads%250Apushkey%250Aremote-changegroup%253Dhttp%252Chttps&cg=0&common=0000000000000000000000000000000000000000&heads=c17445101a72edac06facd130d14808dfbd5c7c2&stream=1"
86 86 200 Script output follows
87 87 content-type: application/mercurial-0.2
88 88
89 89
90 90 $ f --size body --hexdump --bytes 100
91 91 body: size=232
92 92 0000: 04 6e 6f 6e 65 48 47 32 30 00 00 00 00 00 00 00 |.noneHG20.......|
93 93 0010: cf 0b 45 52 52 4f 52 3a 41 42 4f 52 54 00 00 00 |..ERROR:ABORT...|
94 94 0020: 00 01 01 07 3c 04 72 6d 65 73 73 61 67 65 73 74 |....<.rmessagest|
95 95 0030: 72 65 61 6d 20 64 61 74 61 20 72 65 71 75 65 73 |ream data reques|
96 96 0040: 74 65 64 20 62 75 74 20 73 65 72 76 65 72 20 64 |ted but server d|
97 97 0050: 6f 65 73 20 6e 6f 74 20 61 6c 6c 6f 77 20 74 68 |oes not allow th|
98 98 0060: 69 73 20 66 |is f|
99 99
100 100 #endif
101 101 #if stream-bundle2
102 102 $ hg debugcapabilities http://localhost:$HGPORT
103 103 Main capabilities:
104 104 batch
105 105 branchmap
106 106 $USUAL_BUNDLE2_CAPS_SERVER$
107 107 changegroupsubset
108 108 compression=$BUNDLE2_COMPRESSIONS$
109 109 getbundle
110 110 httpheader=1024
111 111 httpmediatype=0.1rx,0.1tx,0.2tx
112 112 known
113 113 lookup
114 114 pushkey
115 115 unbundle=HG10GZ,HG10BZ,HG10UN
116 116 unbundlehash
117 117 Bundle2 capabilities:
118 118 HG20
119 119 bookmarks
120 120 changegroup
121 121 01
122 122 02
123 123 digests
124 124 md5
125 125 sha1
126 126 sha512
127 127 error
128 128 abort
129 129 unsupportedcontent
130 130 pushraced
131 131 pushkey
132 132 hgtagsfnodes
133 133 listkeys
134 134 phases
135 135 heads
136 136 pushkey
137 137 remote-changegroup
138 138 http
139 139 https
140 140 rev-branch-cache
141 141
142 142 $ hg clone --stream -U http://localhost:$HGPORT server-disabled
143 143 warning: stream clone requested but server has them disabled
144 144 requesting all changes
145 145 adding changesets
146 146 adding manifests
147 147 adding file changes
148 148 added 2 changesets with 1025 changes to 1025 files
149 149 new changesets 96ee1d7354c4:c17445101a72
150 150
151 151 $ get-with-headers.py $LOCALIP:$HGPORT '?cmd=getbundle' content-type --bodyfile body --hgproto 0.2 --requestheader "x-hgarg-1=bundlecaps=HG20%2Cbundle2%3DHG20%250Abookmarks%250Achangegroup%253D01%252C02%250Adigests%253Dmd5%252Csha1%252Csha512%250Aerror%253Dabort%252Cunsupportedcontent%252Cpushraced%252Cpushkey%250Ahgtagsfnodes%250Alistkeys%250Aphases%253Dheads%250Apushkey%250Aremote-changegroup%253Dhttp%252Chttps&cg=0&common=0000000000000000000000000000000000000000&heads=c17445101a72edac06facd130d14808dfbd5c7c2&stream=1"
152 152 200 Script output follows
153 153 content-type: application/mercurial-0.2
154 154
155 155
156 156 $ f --size body --hexdump --bytes 100
157 157 body: size=232
158 158 0000: 04 6e 6f 6e 65 48 47 32 30 00 00 00 00 00 00 00 |.noneHG20.......|
159 159 0010: cf 0b 45 52 52 4f 52 3a 41 42 4f 52 54 00 00 00 |..ERROR:ABORT...|
160 160 0020: 00 01 01 07 3c 04 72 6d 65 73 73 61 67 65 73 74 |....<.rmessagest|
161 161 0030: 72 65 61 6d 20 64 61 74 61 20 72 65 71 75 65 73 |ream data reques|
162 162 0040: 74 65 64 20 62 75 74 20 73 65 72 76 65 72 20 64 |ted but server d|
163 163 0050: 6f 65 73 20 6e 6f 74 20 61 6c 6c 6f 77 20 74 68 |oes not allow th|
164 164 0060: 69 73 20 66 |is f|
165 165
166 166 #endif
167 167
168 168 $ killdaemons.py
169 169 $ cd server
170 170 $ hg serve -p $HGPORT -d --pid-file=hg.pid
171 171 $ cat hg.pid > $DAEMON_PIDS
172 172 $ cd ..
173 173
174 174 Basic clone
175 175
176 176 #if stream-legacy
177 177 $ hg clone --stream -U http://localhost:$HGPORT clone1
178 178 streaming all changes
179 179 1027 files to transfer, 96.3 KB of data
180 180 transferred 96.3 KB in * seconds (*/sec) (glob)
181 181 searching for changes
182 182 no changes found
183 183 #endif
184 184 #if stream-bundle2
185 185 $ hg clone --stream -U http://localhost:$HGPORT clone1
186 186 streaming all changes
187 187 1030 files to transfer, 96.4 KB of data
188 188 transferred 96.4 KB in * seconds (* */sec) (glob)
189 189
190 190 $ ls -1 clone1/.hg/cache
191 191 branch2-served
192 192 rbc-names-v1
193 193 rbc-revs-v1
194 194 #endif
195 195
196 196 getbundle requests with stream=1 are uncompressed
197 197
198 198 $ get-with-headers.py $LOCALIP:$HGPORT '?cmd=getbundle' content-type --bodyfile body --hgproto '0.1 0.2 comp=zlib,none' --requestheader "x-hgarg-1=bundlecaps=HG20%2Cbundle2%3DHG20%250Abookmarks%250Achangegroup%253D01%252C02%250Adigests%253Dmd5%252Csha1%252Csha512%250Aerror%253Dabort%252Cunsupportedcontent%252Cpushraced%252Cpushkey%250Ahgtagsfnodes%250Alistkeys%250Aphases%253Dheads%250Apushkey%250Aremote-changegroup%253Dhttp%252Chttps&cg=0&common=0000000000000000000000000000000000000000&heads=c17445101a72edac06facd130d14808dfbd5c7c2&stream=1"
199 199 200 Script output follows
200 200 content-type: application/mercurial-0.2
201 201
202 202
203 203 $ f --size --hex --bytes 256 body
204 204 body: size=112230
205 205 0000: 04 6e 6f 6e 65 48 47 32 30 00 00 00 00 00 00 00 |.noneHG20.......|
206 206 0010: 70 07 53 54 52 45 41 4d 32 00 00 00 00 03 00 09 |p.STREAM2.......|
207 207 0020: 05 09 04 0c 35 62 79 74 65 63 6f 75 6e 74 39 38 |....5bytecount98|
208 208 0030: 37 35 38 66 69 6c 65 63 6f 75 6e 74 31 30 33 30 |758filecount1030|
209 209 0040: 72 65 71 75 69 72 65 6d 65 6e 74 73 64 6f 74 65 |requirementsdote|
210 210 0050: 6e 63 6f 64 65 25 32 43 66 6e 63 61 63 68 65 25 |ncode%2Cfncache%|
211 211 0060: 32 43 67 65 6e 65 72 61 6c 64 65 6c 74 61 25 32 |2Cgeneraldelta%2|
212 212 0070: 43 72 65 76 6c 6f 67 76 31 25 32 43 73 74 6f 72 |Crevlogv1%2Cstor|
213 213 0080: 65 00 00 80 00 73 08 42 64 61 74 61 2f 30 2e 69 |e....s.Bdata/0.i|
214 214 0090: 00 03 00 01 00 00 00 00 00 00 00 02 00 00 00 01 |................|
215 215 00a0: 00 00 00 00 00 00 00 01 ff ff ff ff ff ff ff ff |................|
216 216 00b0: 80 29 63 a0 49 d3 23 87 bf ce fe 56 67 92 67 2c |.)c.I.#....Vg.g,|
217 217 00c0: 69 d1 ec 39 00 00 00 00 00 00 00 00 00 00 00 00 |i..9............|
218 218 00d0: 75 30 73 08 42 64 61 74 61 2f 31 2e 69 00 03 00 |u0s.Bdata/1.i...|
219 219 00e0: 01 00 00 00 00 00 00 00 02 00 00 00 01 00 00 00 |................|
220 220 00f0: 00 00 00 00 01 ff ff ff ff ff ff ff ff f9 76 da |..............v.|
221 221
222 222 --uncompressed is an alias to --stream
223 223
224 224 #if stream-legacy
225 225 $ hg clone --uncompressed -U http://localhost:$HGPORT clone1-uncompressed
226 226 streaming all changes
227 227 1027 files to transfer, 96.3 KB of data
228 228 transferred 96.3 KB in * seconds (*/sec) (glob)
229 229 searching for changes
230 230 no changes found
231 231 #endif
232 232 #if stream-bundle2
233 233 $ hg clone --uncompressed -U http://localhost:$HGPORT clone1-uncompressed
234 234 streaming all changes
235 235 1030 files to transfer, 96.4 KB of data
236 236 transferred 96.4 KB in * seconds (* */sec) (glob)
237 237 #endif
238 238
239 239 Clone with background file closing enabled
240 240
241 241 #if stream-legacy
242 242 $ hg --debug --config worker.backgroundclose=true --config worker.backgroundcloseminfilecount=1 clone --stream -U http://localhost:$HGPORT clone-background | grep -v adding
243 243 using http://localhost:$HGPORT/
244 244 sending capabilities command
245 245 sending branchmap command
246 246 streaming all changes
247 247 sending stream_out command
248 248 1027 files to transfer, 96.3 KB of data
249 249 starting 4 threads for background file closing
250 250 updating the branch cache
251 251 transferred 96.3 KB in * seconds (*/sec) (glob)
252 252 query 1; heads
253 253 sending batch command
254 254 searching for changes
255 255 all remote heads known locally
256 256 no changes found
257 257 sending getbundle command
258 258 bundle2-input-bundle: with-transaction
259 259 bundle2-input-part: "listkeys" (params: 1 mandatory) supported
260 260 bundle2-input-part: "phase-heads" supported
261 261 bundle2-input-part: total payload size 24
262 262 bundle2-input-bundle: 1 parts total
263 263 checking for updated bookmarks
264 264 (sent 5 HTTP requests and * bytes; received * bytes in responses) (glob)
265 265 #endif
266 266 #if stream-bundle2
267 267 $ hg --debug --config worker.backgroundclose=true --config worker.backgroundcloseminfilecount=1 clone --stream -U http://localhost:$HGPORT clone-background | grep -v adding
268 268 using http://localhost:$HGPORT/
269 269 sending capabilities command
270 270 query 1; heads
271 271 sending batch command
272 272 streaming all changes
273 273 sending getbundle command
274 274 bundle2-input-bundle: with-transaction
275 275 bundle2-input-part: "stream2" (params: 3 mandatory) supported
276 276 applying stream bundle
277 277 1030 files to transfer, 96.4 KB of data
278 278 starting 4 threads for background file closing
279 279 starting 4 threads for background file closing
280 280 updating the branch cache
281 281 transferred 96.4 KB in * seconds (* */sec) (glob)
282 282 bundle2-input-part: total payload size 112077
283 283 bundle2-input-part: "listkeys" (params: 1 mandatory) supported
284 284 bundle2-input-bundle: 1 parts total
285 285 checking for updated bookmarks
286 286 (sent 3 HTTP requests and * bytes; received * bytes in responses) (glob)
287 287 #endif
288 288
289 289 Cannot stream clone when there are secret changesets
290 290
291 291 $ hg -R server phase --force --secret -r tip
292 292 $ hg clone --stream -U http://localhost:$HGPORT secret-denied
293 293 warning: stream clone requested but server has them disabled
294 294 requesting all changes
295 295 adding changesets
296 296 adding manifests
297 297 adding file changes
298 298 added 1 changesets with 1 changes to 1 files
299 299 new changesets 96ee1d7354c4
300 300
301 301 $ killdaemons.py
302 302
303 303 Streaming of secrets can be overridden by server config
304 304
305 305 $ cd server
306 306 $ hg serve --config server.uncompressedallowsecret=true -p $HGPORT -d --pid-file=hg.pid
307 307 $ cat hg.pid > $DAEMON_PIDS
308 308 $ cd ..
309 309
310 310 #if stream-legacy
311 311 $ hg clone --stream -U http://localhost:$HGPORT secret-allowed
312 312 streaming all changes
313 313 1027 files to transfer, 96.3 KB of data
314 314 transferred 96.3 KB in * seconds (*/sec) (glob)
315 315 searching for changes
316 316 no changes found
317 317 #endif
318 318 #if stream-bundle2
319 319 $ hg clone --stream -U http://localhost:$HGPORT secret-allowed
320 320 streaming all changes
321 321 1030 files to transfer, 96.4 KB of data
322 322 transferred 96.4 KB in * seconds (* */sec) (glob)
323 323 #endif
324 324
325 325 $ killdaemons.py
326 326
327 327 Verify interaction between preferuncompressed and secret presence
328 328
329 329 $ cd server
330 330 $ hg serve --config server.preferuncompressed=true -p $HGPORT -d --pid-file=hg.pid
331 331 $ cat hg.pid > $DAEMON_PIDS
332 332 $ cd ..
333 333
334 334 $ hg clone -U http://localhost:$HGPORT preferuncompressed-secret
335 335 requesting all changes
336 336 adding changesets
337 337 adding manifests
338 338 adding file changes
339 339 added 1 changesets with 1 changes to 1 files
340 340 new changesets 96ee1d7354c4
341 341
342 342 $ killdaemons.py
343 343
344 344 Clone not allowed when full bundles disabled and can't serve secrets
345 345
346 346 $ cd server
347 347 $ hg serve --config server.disablefullbundle=true -p $HGPORT -d --pid-file=hg.pid
348 348 $ cat hg.pid > $DAEMON_PIDS
349 349 $ cd ..
350 350
351 351 $ hg clone --stream http://localhost:$HGPORT secret-full-disabled
352 352 warning: stream clone requested but server has them disabled
353 353 requesting all changes
354 354 remote: abort: server has pull-based clones disabled
355 355 abort: pull failed on remote
356 356 (remove --pull if specified or upgrade Mercurial)
357 357 [255]
358 358
359 359 Local stream clone with secrets involved
360 360 (This is just a test over behavior: if you have access to the repo's files,
361 361 there is no security so it isn't important to prevent a clone here.)
362 362
363 363 $ hg clone -U --stream server local-secret
364 364 warning: stream clone requested but server has them disabled
365 365 requesting all changes
366 366 adding changesets
367 367 adding manifests
368 368 adding file changes
369 369 added 1 changesets with 1 changes to 1 files
370 370 new changesets 96ee1d7354c4
371 371
372 372 Stream clone while repo is changing:
373 373
374 374 $ mkdir changing
375 375 $ cd changing
376 376
377 377 extension for delaying the server process so we reliably can modify the repo
378 378 while cloning
379 379
380 380 $ cat > delayer.py <<EOF
381 381 > import time
382 382 > from mercurial import extensions, vfs
383 383 > def __call__(orig, self, path, *args, **kwargs):
384 384 > if path == 'data/f1.i':
385 385 > time.sleep(2)
386 386 > return orig(self, path, *args, **kwargs)
387 387 > extensions.wrapfunction(vfs.vfs, '__call__', __call__)
388 388 > EOF
389 389
390 390 prepare repo with small and big file to cover both code paths in emitrevlogdata
391 391
392 392 $ hg init repo
393 393 $ touch repo/f1
394 394 $ $TESTDIR/seq.py 50000 > repo/f2
395 395 $ hg -R repo ci -Aqm "0"
396 396 $ hg serve -R repo -p $HGPORT1 -d --pid-file=hg.pid --config extensions.delayer=delayer.py
397 397 $ cat hg.pid >> $DAEMON_PIDS
398 398
399 399 clone while modifying the repo between stating file with write lock and
400 400 actually serving file content
401 401
402 402 $ hg clone -q --stream -U http://localhost:$HGPORT1 clone &
403 403 $ sleep 1
404 404 $ echo >> repo/f1
405 405 $ echo >> repo/f2
406 406 $ hg -R repo ci -m "1"
407 407 $ wait
408 408 $ hg -R clone id
409 409 000000000000
410 410 $ cd ..
411 411
412 412 Stream repository with bookmarks
413 413 --------------------------------
414 414
415 415 (revert introduction of secret changeset)
416 416
417 417 $ hg -R server phase --draft 'secret()'
418 418
419 419 add a bookmark
420 420
421 421 $ hg -R server bookmark -r tip some-bookmark
422 422
423 423 clone it
424 424
425 425 #if stream-legacy
426 426 $ hg clone --stream http://localhost:$HGPORT with-bookmarks
427 427 streaming all changes
428 428 1027 files to transfer, 96.3 KB of data
429 429 transferred 96.3 KB in * seconds (*) (glob)
430 430 searching for changes
431 431 no changes found
432 432 updating to branch default
433 433 1025 files updated, 0 files merged, 0 files removed, 0 files unresolved
434 434 #endif
435 435 #if stream-bundle2
436 436 $ hg clone --stream http://localhost:$HGPORT with-bookmarks
437 437 streaming all changes
438 438 1033 files to transfer, 96.6 KB of data
439 439 transferred 96.6 KB in * seconds (* */sec) (glob)
440 440 updating to branch default
441 441 1025 files updated, 0 files merged, 0 files removed, 0 files unresolved
442 442 #endif
443 443 $ hg -R with-bookmarks bookmarks
444 444 some-bookmark 1:c17445101a72
445 445
446 446 Stream repository with phases
447 447 -----------------------------
448 448
449 449 Clone as publishing
450 450
451 451 $ hg -R server phase -r 'all()'
452 452 0: draft
453 453 1: draft
454 454
455 455 #if stream-legacy
456 456 $ hg clone --stream http://localhost:$HGPORT phase-publish
457 457 streaming all changes
458 458 1027 files to transfer, 96.3 KB of data
459 459 transferred 96.3 KB in * seconds (*) (glob)
460 460 searching for changes
461 461 no changes found
462 462 updating to branch default
463 463 1025 files updated, 0 files merged, 0 files removed, 0 files unresolved
464 464 #endif
465 465 #if stream-bundle2
466 466 $ hg clone --stream http://localhost:$HGPORT phase-publish
467 467 streaming all changes
468 468 1033 files to transfer, 96.6 KB of data
469 469 transferred 96.6 KB in * seconds (* */sec) (glob)
470 470 updating to branch default
471 471 1025 files updated, 0 files merged, 0 files removed, 0 files unresolved
472 472 #endif
473 473 $ hg -R phase-publish phase -r 'all()'
474 474 0: public
475 475 1: public
476 476
477 477 Clone as non publishing
478 478
479 479 $ cat << EOF >> server/.hg/hgrc
480 480 > [phases]
481 481 > publish = False
482 482 > EOF
483 483 $ killdaemons.py
484 484 $ hg -R server serve -p $HGPORT -d --pid-file=hg.pid
485 485 $ cat hg.pid > $DAEMON_PIDS
486 486
487 487 #if stream-legacy
488 488
489 489 With v1 of the stream protocol, changeset are always cloned as public. It make
490 490 stream v1 unsuitable for non-publishing repository.
491 491
492 492 $ hg clone --stream http://localhost:$HGPORT phase-no-publish
493 493 streaming all changes
494 494 1027 files to transfer, 96.3 KB of data
495 495 transferred 96.3 KB in * seconds (*) (glob)
496 496 searching for changes
497 497 no changes found
498 498 updating to branch default
499 499 1025 files updated, 0 files merged, 0 files removed, 0 files unresolved
500 500 $ hg -R phase-no-publish phase -r 'all()'
501 501 0: public
502 502 1: public
503 503 #endif
504 504 #if stream-bundle2
505 505 $ hg clone --stream http://localhost:$HGPORT phase-no-publish
506 506 streaming all changes
507 507 1034 files to transfer, 96.7 KB of data
508 508 transferred 96.7 KB in * seconds (* */sec) (glob)
509 509 updating to branch default
510 510 1025 files updated, 0 files merged, 0 files removed, 0 files unresolved
511 511 $ hg -R phase-no-publish phase -r 'all()'
512 512 0: draft
513 513 1: draft
514 514 #endif
515 515
516 516 $ killdaemons.py
517
518 #if stream-legacy
519
520 With v1 of the stream protocol, changeset are always cloned as public. There's
521 no obsolescence markers exchange in stream v1.
522
523 #endif
524 #if stream-bundle2
525
526 Stream repository with obsolescence
527 -----------------------------------
528
529 Clone non-publishing with obsolescence
530
531 $ cat >> $HGRCPATH << EOF
532 > [experimental]
533 > evolution=all
534 > EOF
535
536 $ cd server
537 $ echo foo > foo
538 $ hg -q commit -m 'about to be pruned'
539 $ hg debugobsolete `hg log -r . -T '{node}'` -d '0 0' -u test --record-parents
540 obsoleted 1 changesets
541 $ hg up null -q
542 $ hg log -T '{rev}: {phase}\n'
543 1: draft
544 0: draft
545 $ hg serve -p $HGPORT -d --pid-file=hg.pid
546 $ cat hg.pid > $DAEMON_PIDS
547 $ cd ..
548
549 $ hg clone -U --stream http://localhost:$HGPORT with-obsolescence
550 streaming all changes
551 1035 files to transfer, 97.1 KB of data
552 transferred 97.1 KB in * seconds (* */sec) (glob)
553 $ hg -R with-obsolescence log -T '{rev}: {phase}\n'
554 1: draft
555 0: draft
556 $ hg debugobsolete -R with-obsolescence
557 50382b884f66690b7045cac93a540cba4d4c906f 0 {c17445101a72edac06facd130d14808dfbd5c7c2} (Thu Jan 01 00:00:00 1970 +0000) {'user': 'test'}
558
559 $ killdaemons.py
560
561 #endif
General Comments 0
You need to be logged in to leave comments. Login now