##// END OF EJS Templates
bundle2: also capture reply capability on failure...
Pierre-Yves David -
r25492:219b8ab3 default
parent child Browse files
Show More
@@ -1,1391 +1,1394 b''
1 # bundle2.py - generic container format to transmit arbitrary data.
1 # bundle2.py - generic container format to transmit arbitrary data.
2 #
2 #
3 # Copyright 2013 Facebook, Inc.
3 # Copyright 2013 Facebook, Inc.
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7 """Handling of the new bundle2 format
7 """Handling of the new bundle2 format
8
8
9 The goal of bundle2 is to act as an atomically packet to transmit a set of
9 The goal of bundle2 is to act as an atomically packet to transmit a set of
10 payloads in an application agnostic way. It consist in a sequence of "parts"
10 payloads in an application agnostic way. It consist in a sequence of "parts"
11 that will be handed to and processed by the application layer.
11 that will be handed to and processed by the application layer.
12
12
13
13
14 General format architecture
14 General format architecture
15 ===========================
15 ===========================
16
16
17 The format is architectured as follow
17 The format is architectured as follow
18
18
19 - magic string
19 - magic string
20 - stream level parameters
20 - stream level parameters
21 - payload parts (any number)
21 - payload parts (any number)
22 - end of stream marker.
22 - end of stream marker.
23
23
24 the Binary format
24 the Binary format
25 ============================
25 ============================
26
26
27 All numbers are unsigned and big-endian.
27 All numbers are unsigned and big-endian.
28
28
29 stream level parameters
29 stream level parameters
30 ------------------------
30 ------------------------
31
31
32 Binary format is as follow
32 Binary format is as follow
33
33
34 :params size: int32
34 :params size: int32
35
35
36 The total number of Bytes used by the parameters
36 The total number of Bytes used by the parameters
37
37
38 :params value: arbitrary number of Bytes
38 :params value: arbitrary number of Bytes
39
39
40 A blob of `params size` containing the serialized version of all stream level
40 A blob of `params size` containing the serialized version of all stream level
41 parameters.
41 parameters.
42
42
43 The blob contains a space separated list of parameters. Parameters with value
43 The blob contains a space separated list of parameters. Parameters with value
44 are stored in the form `<name>=<value>`. Both name and value are urlquoted.
44 are stored in the form `<name>=<value>`. Both name and value are urlquoted.
45
45
46 Empty name are obviously forbidden.
46 Empty name are obviously forbidden.
47
47
48 Name MUST start with a letter. If this first letter is lower case, the
48 Name MUST start with a letter. If this first letter is lower case, the
49 parameter is advisory and can be safely ignored. However when the first
49 parameter is advisory and can be safely ignored. However when the first
50 letter is capital, the parameter is mandatory and the bundling process MUST
50 letter is capital, the parameter is mandatory and the bundling process MUST
51 stop if he is not able to proceed it.
51 stop if he is not able to proceed it.
52
52
53 Stream parameters use a simple textual format for two main reasons:
53 Stream parameters use a simple textual format for two main reasons:
54
54
55 - Stream level parameters should remain simple and we want to discourage any
55 - Stream level parameters should remain simple and we want to discourage any
56 crazy usage.
56 crazy usage.
57 - Textual data allow easy human inspection of a bundle2 header in case of
57 - Textual data allow easy human inspection of a bundle2 header in case of
58 troubles.
58 troubles.
59
59
60 Any Applicative level options MUST go into a bundle2 part instead.
60 Any Applicative level options MUST go into a bundle2 part instead.
61
61
62 Payload part
62 Payload part
63 ------------------------
63 ------------------------
64
64
65 Binary format is as follow
65 Binary format is as follow
66
66
67 :header size: int32
67 :header size: int32
68
68
69 The total number of Bytes used by the part headers. When the header is empty
69 The total number of Bytes used by the part headers. When the header is empty
70 (size = 0) this is interpreted as the end of stream marker.
70 (size = 0) this is interpreted as the end of stream marker.
71
71
72 :header:
72 :header:
73
73
74 The header defines how to interpret the part. It contains two piece of
74 The header defines how to interpret the part. It contains two piece of
75 data: the part type, and the part parameters.
75 data: the part type, and the part parameters.
76
76
77 The part type is used to route an application level handler, that can
77 The part type is used to route an application level handler, that can
78 interpret payload.
78 interpret payload.
79
79
80 Part parameters are passed to the application level handler. They are
80 Part parameters are passed to the application level handler. They are
81 meant to convey information that will help the application level object to
81 meant to convey information that will help the application level object to
82 interpret the part payload.
82 interpret the part payload.
83
83
84 The binary format of the header is has follow
84 The binary format of the header is has follow
85
85
86 :typesize: (one byte)
86 :typesize: (one byte)
87
87
88 :parttype: alphanumerical part name (restricted to [a-zA-Z0-9_:-]*)
88 :parttype: alphanumerical part name (restricted to [a-zA-Z0-9_:-]*)
89
89
90 :partid: A 32bits integer (unique in the bundle) that can be used to refer
90 :partid: A 32bits integer (unique in the bundle) that can be used to refer
91 to this part.
91 to this part.
92
92
93 :parameters:
93 :parameters:
94
94
95 Part's parameter may have arbitrary content, the binary structure is::
95 Part's parameter may have arbitrary content, the binary structure is::
96
96
97 <mandatory-count><advisory-count><param-sizes><param-data>
97 <mandatory-count><advisory-count><param-sizes><param-data>
98
98
99 :mandatory-count: 1 byte, number of mandatory parameters
99 :mandatory-count: 1 byte, number of mandatory parameters
100
100
101 :advisory-count: 1 byte, number of advisory parameters
101 :advisory-count: 1 byte, number of advisory parameters
102
102
103 :param-sizes:
103 :param-sizes:
104
104
105 N couple of bytes, where N is the total number of parameters. Each
105 N couple of bytes, where N is the total number of parameters. Each
106 couple contains (<size-of-key>, <size-of-value) for one parameter.
106 couple contains (<size-of-key>, <size-of-value) for one parameter.
107
107
108 :param-data:
108 :param-data:
109
109
110 A blob of bytes from which each parameter key and value can be
110 A blob of bytes from which each parameter key and value can be
111 retrieved using the list of size couples stored in the previous
111 retrieved using the list of size couples stored in the previous
112 field.
112 field.
113
113
114 Mandatory parameters comes first, then the advisory ones.
114 Mandatory parameters comes first, then the advisory ones.
115
115
116 Each parameter's key MUST be unique within the part.
116 Each parameter's key MUST be unique within the part.
117
117
118 :payload:
118 :payload:
119
119
120 payload is a series of `<chunksize><chunkdata>`.
120 payload is a series of `<chunksize><chunkdata>`.
121
121
122 `chunksize` is an int32, `chunkdata` are plain bytes (as much as
122 `chunksize` is an int32, `chunkdata` are plain bytes (as much as
123 `chunksize` says)` The payload part is concluded by a zero size chunk.
123 `chunksize` says)` The payload part is concluded by a zero size chunk.
124
124
125 The current implementation always produces either zero or one chunk.
125 The current implementation always produces either zero or one chunk.
126 This is an implementation limitation that will ultimately be lifted.
126 This is an implementation limitation that will ultimately be lifted.
127
127
128 `chunksize` can be negative to trigger special case processing. No such
128 `chunksize` can be negative to trigger special case processing. No such
129 processing is in place yet.
129 processing is in place yet.
130
130
131 Bundle processing
131 Bundle processing
132 ============================
132 ============================
133
133
134 Each part is processed in order using a "part handler". Handler are registered
134 Each part is processed in order using a "part handler". Handler are registered
135 for a certain part type.
135 for a certain part type.
136
136
137 The matching of a part to its handler is case insensitive. The case of the
137 The matching of a part to its handler is case insensitive. The case of the
138 part type is used to know if a part is mandatory or advisory. If the Part type
138 part type is used to know if a part is mandatory or advisory. If the Part type
139 contains any uppercase char it is considered mandatory. When no handler is
139 contains any uppercase char it is considered mandatory. When no handler is
140 known for a Mandatory part, the process is aborted and an exception is raised.
140 known for a Mandatory part, the process is aborted and an exception is raised.
141 If the part is advisory and no handler is known, the part is ignored. When the
141 If the part is advisory and no handler is known, the part is ignored. When the
142 process is aborted, the full bundle is still read from the stream to keep the
142 process is aborted, the full bundle is still read from the stream to keep the
143 channel usable. But none of the part read from an abort are processed. In the
143 channel usable. But none of the part read from an abort are processed. In the
144 future, dropping the stream may become an option for channel we do not care to
144 future, dropping the stream may become an option for channel we do not care to
145 preserve.
145 preserve.
146 """
146 """
147
147
148 import errno
148 import errno
149 import sys
149 import sys
150 import util
150 import util
151 import struct
151 import struct
152 import urllib
152 import urllib
153 import string
153 import string
154 import obsolete
154 import obsolete
155 import pushkey
155 import pushkey
156 import url
156 import url
157 import re
157 import re
158
158
159 import changegroup, error, tags
159 import changegroup, error, tags
160 from i18n import _
160 from i18n import _
161
161
162 _pack = struct.pack
162 _pack = struct.pack
163 _unpack = struct.unpack
163 _unpack = struct.unpack
164
164
165 _fstreamparamsize = '>i'
165 _fstreamparamsize = '>i'
166 _fpartheadersize = '>i'
166 _fpartheadersize = '>i'
167 _fparttypesize = '>B'
167 _fparttypesize = '>B'
168 _fpartid = '>I'
168 _fpartid = '>I'
169 _fpayloadsize = '>i'
169 _fpayloadsize = '>i'
170 _fpartparamcount = '>BB'
170 _fpartparamcount = '>BB'
171
171
172 preferedchunksize = 4096
172 preferedchunksize = 4096
173
173
174 _parttypeforbidden = re.compile('[^a-zA-Z0-9_:-]')
174 _parttypeforbidden = re.compile('[^a-zA-Z0-9_:-]')
175
175
176 def outdebug(ui, message):
176 def outdebug(ui, message):
177 """debug regarding output stream (bundling)"""
177 """debug regarding output stream (bundling)"""
178 if ui.configbool('devel', 'bundle2.debug', False):
178 if ui.configbool('devel', 'bundle2.debug', False):
179 ui.debug('bundle2-output: %s\n' % message)
179 ui.debug('bundle2-output: %s\n' % message)
180
180
181 def indebug(ui, message):
181 def indebug(ui, message):
182 """debug on input stream (unbundling)"""
182 """debug on input stream (unbundling)"""
183 if ui.configbool('devel', 'bundle2.debug', False):
183 if ui.configbool('devel', 'bundle2.debug', False):
184 ui.debug('bundle2-input: %s\n' % message)
184 ui.debug('bundle2-input: %s\n' % message)
185
185
186 def validateparttype(parttype):
186 def validateparttype(parttype):
187 """raise ValueError if a parttype contains invalid character"""
187 """raise ValueError if a parttype contains invalid character"""
188 if _parttypeforbidden.search(parttype):
188 if _parttypeforbidden.search(parttype):
189 raise ValueError(parttype)
189 raise ValueError(parttype)
190
190
191 def _makefpartparamsizes(nbparams):
191 def _makefpartparamsizes(nbparams):
192 """return a struct format to read part parameter sizes
192 """return a struct format to read part parameter sizes
193
193
194 The number parameters is variable so we need to build that format
194 The number parameters is variable so we need to build that format
195 dynamically.
195 dynamically.
196 """
196 """
197 return '>'+('BB'*nbparams)
197 return '>'+('BB'*nbparams)
198
198
199 parthandlermapping = {}
199 parthandlermapping = {}
200
200
201 def parthandler(parttype, params=()):
201 def parthandler(parttype, params=()):
202 """decorator that register a function as a bundle2 part handler
202 """decorator that register a function as a bundle2 part handler
203
203
204 eg::
204 eg::
205
205
206 @parthandler('myparttype', ('mandatory', 'param', 'handled'))
206 @parthandler('myparttype', ('mandatory', 'param', 'handled'))
207 def myparttypehandler(...):
207 def myparttypehandler(...):
208 '''process a part of type "my part".'''
208 '''process a part of type "my part".'''
209 ...
209 ...
210 """
210 """
211 validateparttype(parttype)
211 validateparttype(parttype)
212 def _decorator(func):
212 def _decorator(func):
213 lparttype = parttype.lower() # enforce lower case matching.
213 lparttype = parttype.lower() # enforce lower case matching.
214 assert lparttype not in parthandlermapping
214 assert lparttype not in parthandlermapping
215 parthandlermapping[lparttype] = func
215 parthandlermapping[lparttype] = func
216 func.params = frozenset(params)
216 func.params = frozenset(params)
217 return func
217 return func
218 return _decorator
218 return _decorator
219
219
220 class unbundlerecords(object):
220 class unbundlerecords(object):
221 """keep record of what happens during and unbundle
221 """keep record of what happens during and unbundle
222
222
223 New records are added using `records.add('cat', obj)`. Where 'cat' is a
223 New records are added using `records.add('cat', obj)`. Where 'cat' is a
224 category of record and obj is an arbitrary object.
224 category of record and obj is an arbitrary object.
225
225
226 `records['cat']` will return all entries of this category 'cat'.
226 `records['cat']` will return all entries of this category 'cat'.
227
227
228 Iterating on the object itself will yield `('category', obj)` tuples
228 Iterating on the object itself will yield `('category', obj)` tuples
229 for all entries.
229 for all entries.
230
230
231 All iterations happens in chronological order.
231 All iterations happens in chronological order.
232 """
232 """
233
233
234 def __init__(self):
234 def __init__(self):
235 self._categories = {}
235 self._categories = {}
236 self._sequences = []
236 self._sequences = []
237 self._replies = {}
237 self._replies = {}
238
238
239 def add(self, category, entry, inreplyto=None):
239 def add(self, category, entry, inreplyto=None):
240 """add a new record of a given category.
240 """add a new record of a given category.
241
241
242 The entry can then be retrieved in the list returned by
242 The entry can then be retrieved in the list returned by
243 self['category']."""
243 self['category']."""
244 self._categories.setdefault(category, []).append(entry)
244 self._categories.setdefault(category, []).append(entry)
245 self._sequences.append((category, entry))
245 self._sequences.append((category, entry))
246 if inreplyto is not None:
246 if inreplyto is not None:
247 self.getreplies(inreplyto).add(category, entry)
247 self.getreplies(inreplyto).add(category, entry)
248
248
249 def getreplies(self, partid):
249 def getreplies(self, partid):
250 """get the records that are replies to a specific part"""
250 """get the records that are replies to a specific part"""
251 return self._replies.setdefault(partid, unbundlerecords())
251 return self._replies.setdefault(partid, unbundlerecords())
252
252
253 def __getitem__(self, cat):
253 def __getitem__(self, cat):
254 return tuple(self._categories.get(cat, ()))
254 return tuple(self._categories.get(cat, ()))
255
255
256 def __iter__(self):
256 def __iter__(self):
257 return iter(self._sequences)
257 return iter(self._sequences)
258
258
259 def __len__(self):
259 def __len__(self):
260 return len(self._sequences)
260 return len(self._sequences)
261
261
262 def __nonzero__(self):
262 def __nonzero__(self):
263 return bool(self._sequences)
263 return bool(self._sequences)
264
264
265 class bundleoperation(object):
265 class bundleoperation(object):
266 """an object that represents a single bundling process
266 """an object that represents a single bundling process
267
267
268 Its purpose is to carry unbundle-related objects and states.
268 Its purpose is to carry unbundle-related objects and states.
269
269
270 A new object should be created at the beginning of each bundle processing.
270 A new object should be created at the beginning of each bundle processing.
271 The object is to be returned by the processing function.
271 The object is to be returned by the processing function.
272
272
273 The object has very little content now it will ultimately contain:
273 The object has very little content now it will ultimately contain:
274 * an access to the repo the bundle is applied to,
274 * an access to the repo the bundle is applied to,
275 * a ui object,
275 * a ui object,
276 * a way to retrieve a transaction to add changes to the repo,
276 * a way to retrieve a transaction to add changes to the repo,
277 * a way to record the result of processing each part,
277 * a way to record the result of processing each part,
278 * a way to construct a bundle response when applicable.
278 * a way to construct a bundle response when applicable.
279 """
279 """
280
280
281 def __init__(self, repo, transactiongetter, captureoutput=True):
281 def __init__(self, repo, transactiongetter, captureoutput=True):
282 self.repo = repo
282 self.repo = repo
283 self.ui = repo.ui
283 self.ui = repo.ui
284 self.records = unbundlerecords()
284 self.records = unbundlerecords()
285 self.gettransaction = transactiongetter
285 self.gettransaction = transactiongetter
286 self.reply = None
286 self.reply = None
287 self.captureoutput = captureoutput
287 self.captureoutput = captureoutput
288
288
289 class TransactionUnavailable(RuntimeError):
289 class TransactionUnavailable(RuntimeError):
290 pass
290 pass
291
291
292 def _notransaction():
292 def _notransaction():
293 """default method to get a transaction while processing a bundle
293 """default method to get a transaction while processing a bundle
294
294
295 Raise an exception to highlight the fact that no transaction was expected
295 Raise an exception to highlight the fact that no transaction was expected
296 to be created"""
296 to be created"""
297 raise TransactionUnavailable()
297 raise TransactionUnavailable()
298
298
299 def processbundle(repo, unbundler, transactiongetter=None, op=None):
299 def processbundle(repo, unbundler, transactiongetter=None, op=None):
300 """This function process a bundle, apply effect to/from a repo
300 """This function process a bundle, apply effect to/from a repo
301
301
302 It iterates over each part then searches for and uses the proper handling
302 It iterates over each part then searches for and uses the proper handling
303 code to process the part. Parts are processed in order.
303 code to process the part. Parts are processed in order.
304
304
305 This is very early version of this function that will be strongly reworked
305 This is very early version of this function that will be strongly reworked
306 before final usage.
306 before final usage.
307
307
308 Unknown Mandatory part will abort the process.
308 Unknown Mandatory part will abort the process.
309
309
310 It is temporarily possible to provide a prebuilt bundleoperation to the
310 It is temporarily possible to provide a prebuilt bundleoperation to the
311 function. This is used to ensure output is properly propagated in case of
311 function. This is used to ensure output is properly propagated in case of
312 an error during the unbundling. This output capturing part will likely be
312 an error during the unbundling. This output capturing part will likely be
313 reworked and this ability will probably go away in the process.
313 reworked and this ability will probably go away in the process.
314 """
314 """
315 if op is None:
315 if op is None:
316 if transactiongetter is None:
316 if transactiongetter is None:
317 transactiongetter = _notransaction
317 transactiongetter = _notransaction
318 op = bundleoperation(repo, transactiongetter)
318 op = bundleoperation(repo, transactiongetter)
319 # todo:
319 # todo:
320 # - replace this is a init function soon.
320 # - replace this is a init function soon.
321 # - exception catching
321 # - exception catching
322 unbundler.params
322 unbundler.params
323 if repo.ui.debugflag:
323 if repo.ui.debugflag:
324 msg = ['bundle2-input-bundle:']
324 msg = ['bundle2-input-bundle:']
325 if unbundler.params:
325 if unbundler.params:
326 msg.append(' %i params')
326 msg.append(' %i params')
327 if op.gettransaction is None:
327 if op.gettransaction is None:
328 msg.append(' no-transaction')
328 msg.append(' no-transaction')
329 else:
329 else:
330 msg.append(' with-transaction')
330 msg.append(' with-transaction')
331 msg.append('\n')
331 msg.append('\n')
332 repo.ui.debug(''.join(msg))
332 repo.ui.debug(''.join(msg))
333 iterparts = enumerate(unbundler.iterparts())
333 iterparts = enumerate(unbundler.iterparts())
334 part = None
334 part = None
335 nbpart = 0
335 nbpart = 0
336 try:
336 try:
337 for nbpart, part in iterparts:
337 for nbpart, part in iterparts:
338 _processpart(op, part)
338 _processpart(op, part)
339 except BaseException, exc:
339 except BaseException, exc:
340 for nbpart, part in iterparts:
340 for nbpart, part in iterparts:
341 # consume the bundle content
341 # consume the bundle content
342 part.seek(0, 2)
342 part.seek(0, 2)
343 # Small hack to let caller code distinguish exceptions from bundle2
343 # Small hack to let caller code distinguish exceptions from bundle2
344 # processing from processing the old format. This is mostly
344 # processing from processing the old format. This is mostly
345 # needed to handle different return codes to unbundle according to the
345 # needed to handle different return codes to unbundle according to the
346 # type of bundle. We should probably clean up or drop this return code
346 # type of bundle. We should probably clean up or drop this return code
347 # craziness in a future version.
347 # craziness in a future version.
348 exc.duringunbundle2 = True
348 exc.duringunbundle2 = True
349 salvaged = []
349 salvaged = []
350 replycaps = None
350 if op.reply is not None:
351 if op.reply is not None:
351 salvaged = op.reply.salvageoutput()
352 salvaged = op.reply.salvageoutput()
353 replycaps = op.reply.capabilities
354 exc._replycaps = replycaps
352 exc._bundle2salvagedoutput = salvaged
355 exc._bundle2salvagedoutput = salvaged
353 raise
356 raise
354 finally:
357 finally:
355 repo.ui.debug('bundle2-input-bundle: %i parts total\n' % nbpart)
358 repo.ui.debug('bundle2-input-bundle: %i parts total\n' % nbpart)
356
359
357 return op
360 return op
358
361
359 def _processpart(op, part):
362 def _processpart(op, part):
360 """process a single part from a bundle
363 """process a single part from a bundle
361
364
362 The part is guaranteed to have been fully consumed when the function exits
365 The part is guaranteed to have been fully consumed when the function exits
363 (even if an exception is raised)."""
366 (even if an exception is raised)."""
364 status = 'unknown' # used by debug output
367 status = 'unknown' # used by debug output
365 try:
368 try:
366 try:
369 try:
367 handler = parthandlermapping.get(part.type)
370 handler = parthandlermapping.get(part.type)
368 if handler is None:
371 if handler is None:
369 status = 'unsupported-type'
372 status = 'unsupported-type'
370 raise error.UnsupportedPartError(parttype=part.type)
373 raise error.UnsupportedPartError(parttype=part.type)
371 indebug(op.ui, 'found a handler for part %r' % part.type)
374 indebug(op.ui, 'found a handler for part %r' % part.type)
372 unknownparams = part.mandatorykeys - handler.params
375 unknownparams = part.mandatorykeys - handler.params
373 if unknownparams:
376 if unknownparams:
374 unknownparams = list(unknownparams)
377 unknownparams = list(unknownparams)
375 unknownparams.sort()
378 unknownparams.sort()
376 status = 'unsupported-params (%s)' % unknownparams
379 status = 'unsupported-params (%s)' % unknownparams
377 raise error.UnsupportedPartError(parttype=part.type,
380 raise error.UnsupportedPartError(parttype=part.type,
378 params=unknownparams)
381 params=unknownparams)
379 status = 'supported'
382 status = 'supported'
380 except error.UnsupportedPartError, exc:
383 except error.UnsupportedPartError, exc:
381 if part.mandatory: # mandatory parts
384 if part.mandatory: # mandatory parts
382 raise
385 raise
383 indebug(op.ui, 'ignoring unsupported advisory part %s' % exc)
386 indebug(op.ui, 'ignoring unsupported advisory part %s' % exc)
384 return # skip to part processing
387 return # skip to part processing
385 finally:
388 finally:
386 if op.ui.debugflag:
389 if op.ui.debugflag:
387 msg = ['bundle2-input-part: "%s"' % part.type]
390 msg = ['bundle2-input-part: "%s"' % part.type]
388 if not part.mandatory:
391 if not part.mandatory:
389 msg.append(' (advisory)')
392 msg.append(' (advisory)')
390 nbmp = len(part.mandatorykeys)
393 nbmp = len(part.mandatorykeys)
391 nbap = len(part.params) - nbmp
394 nbap = len(part.params) - nbmp
392 if nbmp or nbap:
395 if nbmp or nbap:
393 msg.append(' (params:')
396 msg.append(' (params:')
394 if nbmp:
397 if nbmp:
395 msg.append(' %i mandatory' % nbmp)
398 msg.append(' %i mandatory' % nbmp)
396 if nbap:
399 if nbap:
397 msg.append(' %i advisory' % nbmp)
400 msg.append(' %i advisory' % nbmp)
398 msg.append(')')
401 msg.append(')')
399 msg.append(' %s\n' % status)
402 msg.append(' %s\n' % status)
400 op.ui.debug(''.join(msg))
403 op.ui.debug(''.join(msg))
401
404
402 # handler is called outside the above try block so that we don't
405 # handler is called outside the above try block so that we don't
403 # risk catching KeyErrors from anything other than the
406 # risk catching KeyErrors from anything other than the
404 # parthandlermapping lookup (any KeyError raised by handler()
407 # parthandlermapping lookup (any KeyError raised by handler()
405 # itself represents a defect of a different variety).
408 # itself represents a defect of a different variety).
406 output = None
409 output = None
407 if op.captureoutput and op.reply is not None:
410 if op.captureoutput and op.reply is not None:
408 op.ui.pushbuffer(error=True, subproc=True)
411 op.ui.pushbuffer(error=True, subproc=True)
409 output = ''
412 output = ''
410 try:
413 try:
411 handler(op, part)
414 handler(op, part)
412 finally:
415 finally:
413 if output is not None:
416 if output is not None:
414 output = op.ui.popbuffer()
417 output = op.ui.popbuffer()
415 if output:
418 if output:
416 outpart = op.reply.newpart('output', data=output,
419 outpart = op.reply.newpart('output', data=output,
417 mandatory=False)
420 mandatory=False)
418 outpart.addparam('in-reply-to', str(part.id), mandatory=False)
421 outpart.addparam('in-reply-to', str(part.id), mandatory=False)
419 finally:
422 finally:
420 # consume the part content to not corrupt the stream.
423 # consume the part content to not corrupt the stream.
421 part.seek(0, 2)
424 part.seek(0, 2)
422
425
423
426
424 def decodecaps(blob):
427 def decodecaps(blob):
425 """decode a bundle2 caps bytes blob into a dictionary
428 """decode a bundle2 caps bytes blob into a dictionary
426
429
427 The blob is a list of capabilities (one per line)
430 The blob is a list of capabilities (one per line)
428 Capabilities may have values using a line of the form::
431 Capabilities may have values using a line of the form::
429
432
430 capability=value1,value2,value3
433 capability=value1,value2,value3
431
434
432 The values are always a list."""
435 The values are always a list."""
433 caps = {}
436 caps = {}
434 for line in blob.splitlines():
437 for line in blob.splitlines():
435 if not line:
438 if not line:
436 continue
439 continue
437 if '=' not in line:
440 if '=' not in line:
438 key, vals = line, ()
441 key, vals = line, ()
439 else:
442 else:
440 key, vals = line.split('=', 1)
443 key, vals = line.split('=', 1)
441 vals = vals.split(',')
444 vals = vals.split(',')
442 key = urllib.unquote(key)
445 key = urllib.unquote(key)
443 vals = [urllib.unquote(v) for v in vals]
446 vals = [urllib.unquote(v) for v in vals]
444 caps[key] = vals
447 caps[key] = vals
445 return caps
448 return caps
446
449
447 def encodecaps(caps):
450 def encodecaps(caps):
448 """encode a bundle2 caps dictionary into a bytes blob"""
451 """encode a bundle2 caps dictionary into a bytes blob"""
449 chunks = []
452 chunks = []
450 for ca in sorted(caps):
453 for ca in sorted(caps):
451 vals = caps[ca]
454 vals = caps[ca]
452 ca = urllib.quote(ca)
455 ca = urllib.quote(ca)
453 vals = [urllib.quote(v) for v in vals]
456 vals = [urllib.quote(v) for v in vals]
454 if vals:
457 if vals:
455 ca = "%s=%s" % (ca, ','.join(vals))
458 ca = "%s=%s" % (ca, ','.join(vals))
456 chunks.append(ca)
459 chunks.append(ca)
457 return '\n'.join(chunks)
460 return '\n'.join(chunks)
458
461
459 class bundle20(object):
462 class bundle20(object):
460 """represent an outgoing bundle2 container
463 """represent an outgoing bundle2 container
461
464
462 Use the `addparam` method to add stream level parameter. and `newpart` to
465 Use the `addparam` method to add stream level parameter. and `newpart` to
463 populate it. Then call `getchunks` to retrieve all the binary chunks of
466 populate it. Then call `getchunks` to retrieve all the binary chunks of
464 data that compose the bundle2 container."""
467 data that compose the bundle2 container."""
465
468
466 _magicstring = 'HG20'
469 _magicstring = 'HG20'
467
470
468 def __init__(self, ui, capabilities=()):
471 def __init__(self, ui, capabilities=()):
469 self.ui = ui
472 self.ui = ui
470 self._params = []
473 self._params = []
471 self._parts = []
474 self._parts = []
472 self.capabilities = dict(capabilities)
475 self.capabilities = dict(capabilities)
473
476
474 @property
477 @property
475 def nbparts(self):
478 def nbparts(self):
476 """total number of parts added to the bundler"""
479 """total number of parts added to the bundler"""
477 return len(self._parts)
480 return len(self._parts)
478
481
479 # methods used to defines the bundle2 content
482 # methods used to defines the bundle2 content
480 def addparam(self, name, value=None):
483 def addparam(self, name, value=None):
481 """add a stream level parameter"""
484 """add a stream level parameter"""
482 if not name:
485 if not name:
483 raise ValueError('empty parameter name')
486 raise ValueError('empty parameter name')
484 if name[0] not in string.letters:
487 if name[0] not in string.letters:
485 raise ValueError('non letter first character: %r' % name)
488 raise ValueError('non letter first character: %r' % name)
486 self._params.append((name, value))
489 self._params.append((name, value))
487
490
488 def addpart(self, part):
491 def addpart(self, part):
489 """add a new part to the bundle2 container
492 """add a new part to the bundle2 container
490
493
491 Parts contains the actual applicative payload."""
494 Parts contains the actual applicative payload."""
492 assert part.id is None
495 assert part.id is None
493 part.id = len(self._parts) # very cheap counter
496 part.id = len(self._parts) # very cheap counter
494 self._parts.append(part)
497 self._parts.append(part)
495
498
496 def newpart(self, typeid, *args, **kwargs):
499 def newpart(self, typeid, *args, **kwargs):
497 """create a new part and add it to the containers
500 """create a new part and add it to the containers
498
501
499 As the part is directly added to the containers. For now, this means
502 As the part is directly added to the containers. For now, this means
500 that any failure to properly initialize the part after calling
503 that any failure to properly initialize the part after calling
501 ``newpart`` should result in a failure of the whole bundling process.
504 ``newpart`` should result in a failure of the whole bundling process.
502
505
503 You can still fall back to manually create and add if you need better
506 You can still fall back to manually create and add if you need better
504 control."""
507 control."""
505 part = bundlepart(typeid, *args, **kwargs)
508 part = bundlepart(typeid, *args, **kwargs)
506 self.addpart(part)
509 self.addpart(part)
507 return part
510 return part
508
511
509 # methods used to generate the bundle2 stream
512 # methods used to generate the bundle2 stream
510 def getchunks(self):
513 def getchunks(self):
511 if self.ui.debugflag:
514 if self.ui.debugflag:
512 msg = ['bundle2-output-bundle: "%s",' % self._magicstring]
515 msg = ['bundle2-output-bundle: "%s",' % self._magicstring]
513 if self._params:
516 if self._params:
514 msg.append(' (%i params)' % len(self._params))
517 msg.append(' (%i params)' % len(self._params))
515 msg.append(' %i parts total\n' % len(self._parts))
518 msg.append(' %i parts total\n' % len(self._parts))
516 self.ui.debug(''.join(msg))
519 self.ui.debug(''.join(msg))
517 outdebug(self.ui, 'start emission of %s stream' % self._magicstring)
520 outdebug(self.ui, 'start emission of %s stream' % self._magicstring)
518 yield self._magicstring
521 yield self._magicstring
519 param = self._paramchunk()
522 param = self._paramchunk()
520 outdebug(self.ui, 'bundle parameter: %s' % param)
523 outdebug(self.ui, 'bundle parameter: %s' % param)
521 yield _pack(_fstreamparamsize, len(param))
524 yield _pack(_fstreamparamsize, len(param))
522 if param:
525 if param:
523 yield param
526 yield param
524
527
525 outdebug(self.ui, 'start of parts')
528 outdebug(self.ui, 'start of parts')
526 for part in self._parts:
529 for part in self._parts:
527 outdebug(self.ui, 'bundle part: "%s"' % part.type)
530 outdebug(self.ui, 'bundle part: "%s"' % part.type)
528 for chunk in part.getchunks(ui=self.ui):
531 for chunk in part.getchunks(ui=self.ui):
529 yield chunk
532 yield chunk
530 outdebug(self.ui, 'end of bundle')
533 outdebug(self.ui, 'end of bundle')
531 yield _pack(_fpartheadersize, 0)
534 yield _pack(_fpartheadersize, 0)
532
535
533 def _paramchunk(self):
536 def _paramchunk(self):
534 """return a encoded version of all stream parameters"""
537 """return a encoded version of all stream parameters"""
535 blocks = []
538 blocks = []
536 for par, value in self._params:
539 for par, value in self._params:
537 par = urllib.quote(par)
540 par = urllib.quote(par)
538 if value is not None:
541 if value is not None:
539 value = urllib.quote(value)
542 value = urllib.quote(value)
540 par = '%s=%s' % (par, value)
543 par = '%s=%s' % (par, value)
541 blocks.append(par)
544 blocks.append(par)
542 return ' '.join(blocks)
545 return ' '.join(blocks)
543
546
544 def salvageoutput(self):
547 def salvageoutput(self):
545 """return a list with a copy of all output parts in the bundle
548 """return a list with a copy of all output parts in the bundle
546
549
547 This is meant to be used during error handling to make sure we preserve
550 This is meant to be used during error handling to make sure we preserve
548 server output"""
551 server output"""
549 salvaged = []
552 salvaged = []
550 for part in self._parts:
553 for part in self._parts:
551 if part.type.startswith('output'):
554 if part.type.startswith('output'):
552 salvaged.append(part.copy())
555 salvaged.append(part.copy())
553 return salvaged
556 return salvaged
554
557
555
558
556 class unpackermixin(object):
559 class unpackermixin(object):
557 """A mixin to extract bytes and struct data from a stream"""
560 """A mixin to extract bytes and struct data from a stream"""
558
561
559 def __init__(self, fp):
562 def __init__(self, fp):
560 self._fp = fp
563 self._fp = fp
561 self._seekable = (util.safehasattr(fp, 'seek') and
564 self._seekable = (util.safehasattr(fp, 'seek') and
562 util.safehasattr(fp, 'tell'))
565 util.safehasattr(fp, 'tell'))
563
566
564 def _unpack(self, format):
567 def _unpack(self, format):
565 """unpack this struct format from the stream"""
568 """unpack this struct format from the stream"""
566 data = self._readexact(struct.calcsize(format))
569 data = self._readexact(struct.calcsize(format))
567 return _unpack(format, data)
570 return _unpack(format, data)
568
571
569 def _readexact(self, size):
572 def _readexact(self, size):
570 """read exactly <size> bytes from the stream"""
573 """read exactly <size> bytes from the stream"""
571 return changegroup.readexactly(self._fp, size)
574 return changegroup.readexactly(self._fp, size)
572
575
573 def seek(self, offset, whence=0):
576 def seek(self, offset, whence=0):
574 """move the underlying file pointer"""
577 """move the underlying file pointer"""
575 if self._seekable:
578 if self._seekable:
576 return self._fp.seek(offset, whence)
579 return self._fp.seek(offset, whence)
577 else:
580 else:
578 raise NotImplementedError(_('File pointer is not seekable'))
581 raise NotImplementedError(_('File pointer is not seekable'))
579
582
580 def tell(self):
583 def tell(self):
581 """return the file offset, or None if file is not seekable"""
584 """return the file offset, or None if file is not seekable"""
582 if self._seekable:
585 if self._seekable:
583 try:
586 try:
584 return self._fp.tell()
587 return self._fp.tell()
585 except IOError, e:
588 except IOError, e:
586 if e.errno == errno.ESPIPE:
589 if e.errno == errno.ESPIPE:
587 self._seekable = False
590 self._seekable = False
588 else:
591 else:
589 raise
592 raise
590 return None
593 return None
591
594
592 def close(self):
595 def close(self):
593 """close underlying file"""
596 """close underlying file"""
594 if util.safehasattr(self._fp, 'close'):
597 if util.safehasattr(self._fp, 'close'):
595 return self._fp.close()
598 return self._fp.close()
596
599
597 def getunbundler(ui, fp, header=None):
600 def getunbundler(ui, fp, header=None):
598 """return a valid unbundler object for a given header"""
601 """return a valid unbundler object for a given header"""
599 if header is None:
602 if header is None:
600 header = changegroup.readexactly(fp, 4)
603 header = changegroup.readexactly(fp, 4)
601 magic, version = header[0:2], header[2:4]
604 magic, version = header[0:2], header[2:4]
602 if magic != 'HG':
605 if magic != 'HG':
603 raise util.Abort(_('not a Mercurial bundle'))
606 raise util.Abort(_('not a Mercurial bundle'))
604 unbundlerclass = formatmap.get(version)
607 unbundlerclass = formatmap.get(version)
605 if unbundlerclass is None:
608 if unbundlerclass is None:
606 raise util.Abort(_('unknown bundle version %s') % version)
609 raise util.Abort(_('unknown bundle version %s') % version)
607 unbundler = unbundlerclass(ui, fp)
610 unbundler = unbundlerclass(ui, fp)
608 indebug(ui, 'start processing of %s stream' % header)
611 indebug(ui, 'start processing of %s stream' % header)
609 return unbundler
612 return unbundler
610
613
611 class unbundle20(unpackermixin):
614 class unbundle20(unpackermixin):
612 """interpret a bundle2 stream
615 """interpret a bundle2 stream
613
616
614 This class is fed with a binary stream and yields parts through its
617 This class is fed with a binary stream and yields parts through its
615 `iterparts` methods."""
618 `iterparts` methods."""
616
619
617 def __init__(self, ui, fp):
620 def __init__(self, ui, fp):
618 """If header is specified, we do not read it out of the stream."""
621 """If header is specified, we do not read it out of the stream."""
619 self.ui = ui
622 self.ui = ui
620 super(unbundle20, self).__init__(fp)
623 super(unbundle20, self).__init__(fp)
621
624
622 @util.propertycache
625 @util.propertycache
623 def params(self):
626 def params(self):
624 """dictionary of stream level parameters"""
627 """dictionary of stream level parameters"""
625 indebug(self.ui, 'reading bundle2 stream parameters')
628 indebug(self.ui, 'reading bundle2 stream parameters')
626 params = {}
629 params = {}
627 paramssize = self._unpack(_fstreamparamsize)[0]
630 paramssize = self._unpack(_fstreamparamsize)[0]
628 if paramssize < 0:
631 if paramssize < 0:
629 raise error.BundleValueError('negative bundle param size: %i'
632 raise error.BundleValueError('negative bundle param size: %i'
630 % paramssize)
633 % paramssize)
631 if paramssize:
634 if paramssize:
632 for p in self._readexact(paramssize).split(' '):
635 for p in self._readexact(paramssize).split(' '):
633 p = p.split('=', 1)
636 p = p.split('=', 1)
634 p = [urllib.unquote(i) for i in p]
637 p = [urllib.unquote(i) for i in p]
635 if len(p) < 2:
638 if len(p) < 2:
636 p.append(None)
639 p.append(None)
637 self._processparam(*p)
640 self._processparam(*p)
638 params[p[0]] = p[1]
641 params[p[0]] = p[1]
639 return params
642 return params
640
643
641 def _processparam(self, name, value):
644 def _processparam(self, name, value):
642 """process a parameter, applying its effect if needed
645 """process a parameter, applying its effect if needed
643
646
644 Parameter starting with a lower case letter are advisory and will be
647 Parameter starting with a lower case letter are advisory and will be
645 ignored when unknown. Those starting with an upper case letter are
648 ignored when unknown. Those starting with an upper case letter are
646 mandatory and will this function will raise a KeyError when unknown.
649 mandatory and will this function will raise a KeyError when unknown.
647
650
648 Note: no option are currently supported. Any input will be either
651 Note: no option are currently supported. Any input will be either
649 ignored or failing.
652 ignored or failing.
650 """
653 """
651 if not name:
654 if not name:
652 raise ValueError('empty parameter name')
655 raise ValueError('empty parameter name')
653 if name[0] not in string.letters:
656 if name[0] not in string.letters:
654 raise ValueError('non letter first character: %r' % name)
657 raise ValueError('non letter first character: %r' % name)
655 # Some logic will be later added here to try to process the option for
658 # Some logic will be later added here to try to process the option for
656 # a dict of known parameter.
659 # a dict of known parameter.
657 if name[0].islower():
660 if name[0].islower():
658 indebug(self.ui, "ignoring unknown parameter %r" % name)
661 indebug(self.ui, "ignoring unknown parameter %r" % name)
659 else:
662 else:
660 raise error.UnsupportedPartError(params=(name,))
663 raise error.UnsupportedPartError(params=(name,))
661
664
662
665
663 def iterparts(self):
666 def iterparts(self):
664 """yield all parts contained in the stream"""
667 """yield all parts contained in the stream"""
665 # make sure param have been loaded
668 # make sure param have been loaded
666 self.params
669 self.params
667 indebug(self.ui, 'start extraction of bundle2 parts')
670 indebug(self.ui, 'start extraction of bundle2 parts')
668 headerblock = self._readpartheader()
671 headerblock = self._readpartheader()
669 while headerblock is not None:
672 while headerblock is not None:
670 part = unbundlepart(self.ui, headerblock, self._fp)
673 part = unbundlepart(self.ui, headerblock, self._fp)
671 yield part
674 yield part
672 part.seek(0, 2)
675 part.seek(0, 2)
673 headerblock = self._readpartheader()
676 headerblock = self._readpartheader()
674 indebug(self.ui, 'end of bundle2 stream')
677 indebug(self.ui, 'end of bundle2 stream')
675
678
676 def _readpartheader(self):
679 def _readpartheader(self):
677 """reads a part header size and return the bytes blob
680 """reads a part header size and return the bytes blob
678
681
679 returns None if empty"""
682 returns None if empty"""
680 headersize = self._unpack(_fpartheadersize)[0]
683 headersize = self._unpack(_fpartheadersize)[0]
681 if headersize < 0:
684 if headersize < 0:
682 raise error.BundleValueError('negative part header size: %i'
685 raise error.BundleValueError('negative part header size: %i'
683 % headersize)
686 % headersize)
684 indebug(self.ui, 'part header size: %i' % headersize)
687 indebug(self.ui, 'part header size: %i' % headersize)
685 if headersize:
688 if headersize:
686 return self._readexact(headersize)
689 return self._readexact(headersize)
687 return None
690 return None
688
691
689 def compressed(self):
692 def compressed(self):
690 return False
693 return False
691
694
692 formatmap = {'20': unbundle20}
695 formatmap = {'20': unbundle20}
693
696
694 class bundlepart(object):
697 class bundlepart(object):
695 """A bundle2 part contains application level payload
698 """A bundle2 part contains application level payload
696
699
697 The part `type` is used to route the part to the application level
700 The part `type` is used to route the part to the application level
698 handler.
701 handler.
699
702
700 The part payload is contained in ``part.data``. It could be raw bytes or a
703 The part payload is contained in ``part.data``. It could be raw bytes or a
701 generator of byte chunks.
704 generator of byte chunks.
702
705
703 You can add parameters to the part using the ``addparam`` method.
706 You can add parameters to the part using the ``addparam`` method.
704 Parameters can be either mandatory (default) or advisory. Remote side
707 Parameters can be either mandatory (default) or advisory. Remote side
705 should be able to safely ignore the advisory ones.
708 should be able to safely ignore the advisory ones.
706
709
707 Both data and parameters cannot be modified after the generation has begun.
710 Both data and parameters cannot be modified after the generation has begun.
708 """
711 """
709
712
710 def __init__(self, parttype, mandatoryparams=(), advisoryparams=(),
713 def __init__(self, parttype, mandatoryparams=(), advisoryparams=(),
711 data='', mandatory=True):
714 data='', mandatory=True):
712 validateparttype(parttype)
715 validateparttype(parttype)
713 self.id = None
716 self.id = None
714 self.type = parttype
717 self.type = parttype
715 self._data = data
718 self._data = data
716 self._mandatoryparams = list(mandatoryparams)
719 self._mandatoryparams = list(mandatoryparams)
717 self._advisoryparams = list(advisoryparams)
720 self._advisoryparams = list(advisoryparams)
718 # checking for duplicated entries
721 # checking for duplicated entries
719 self._seenparams = set()
722 self._seenparams = set()
720 for pname, __ in self._mandatoryparams + self._advisoryparams:
723 for pname, __ in self._mandatoryparams + self._advisoryparams:
721 if pname in self._seenparams:
724 if pname in self._seenparams:
722 raise RuntimeError('duplicated params: %s' % pname)
725 raise RuntimeError('duplicated params: %s' % pname)
723 self._seenparams.add(pname)
726 self._seenparams.add(pname)
724 # status of the part's generation:
727 # status of the part's generation:
725 # - None: not started,
728 # - None: not started,
726 # - False: currently generated,
729 # - False: currently generated,
727 # - True: generation done.
730 # - True: generation done.
728 self._generated = None
731 self._generated = None
729 self.mandatory = mandatory
732 self.mandatory = mandatory
730
733
731 def copy(self):
734 def copy(self):
732 """return a copy of the part
735 """return a copy of the part
733
736
734 The new part have the very same content but no partid assigned yet.
737 The new part have the very same content but no partid assigned yet.
735 Parts with generated data cannot be copied."""
738 Parts with generated data cannot be copied."""
736 assert not util.safehasattr(self.data, 'next')
739 assert not util.safehasattr(self.data, 'next')
737 return self.__class__(self.type, self._mandatoryparams,
740 return self.__class__(self.type, self._mandatoryparams,
738 self._advisoryparams, self._data, self.mandatory)
741 self._advisoryparams, self._data, self.mandatory)
739
742
740 # methods used to defines the part content
743 # methods used to defines the part content
741 def __setdata(self, data):
744 def __setdata(self, data):
742 if self._generated is not None:
745 if self._generated is not None:
743 raise error.ReadOnlyPartError('part is being generated')
746 raise error.ReadOnlyPartError('part is being generated')
744 self._data = data
747 self._data = data
745 def __getdata(self):
748 def __getdata(self):
746 return self._data
749 return self._data
747 data = property(__getdata, __setdata)
750 data = property(__getdata, __setdata)
748
751
749 @property
752 @property
750 def mandatoryparams(self):
753 def mandatoryparams(self):
751 # make it an immutable tuple to force people through ``addparam``
754 # make it an immutable tuple to force people through ``addparam``
752 return tuple(self._mandatoryparams)
755 return tuple(self._mandatoryparams)
753
756
754 @property
757 @property
755 def advisoryparams(self):
758 def advisoryparams(self):
756 # make it an immutable tuple to force people through ``addparam``
759 # make it an immutable tuple to force people through ``addparam``
757 return tuple(self._advisoryparams)
760 return tuple(self._advisoryparams)
758
761
759 def addparam(self, name, value='', mandatory=True):
762 def addparam(self, name, value='', mandatory=True):
760 if self._generated is not None:
763 if self._generated is not None:
761 raise error.ReadOnlyPartError('part is being generated')
764 raise error.ReadOnlyPartError('part is being generated')
762 if name in self._seenparams:
765 if name in self._seenparams:
763 raise ValueError('duplicated params: %s' % name)
766 raise ValueError('duplicated params: %s' % name)
764 self._seenparams.add(name)
767 self._seenparams.add(name)
765 params = self._advisoryparams
768 params = self._advisoryparams
766 if mandatory:
769 if mandatory:
767 params = self._mandatoryparams
770 params = self._mandatoryparams
768 params.append((name, value))
771 params.append((name, value))
769
772
770 # methods used to generates the bundle2 stream
773 # methods used to generates the bundle2 stream
771 def getchunks(self, ui):
774 def getchunks(self, ui):
772 if self._generated is not None:
775 if self._generated is not None:
773 raise RuntimeError('part can only be consumed once')
776 raise RuntimeError('part can only be consumed once')
774 self._generated = False
777 self._generated = False
775
778
776 if ui.debugflag:
779 if ui.debugflag:
777 msg = ['bundle2-output-part: "%s"' % self.type]
780 msg = ['bundle2-output-part: "%s"' % self.type]
778 if not self.mandatory:
781 if not self.mandatory:
779 msg.append(' (advisory)')
782 msg.append(' (advisory)')
780 nbmp = len(self.mandatoryparams)
783 nbmp = len(self.mandatoryparams)
781 nbap = len(self.advisoryparams)
784 nbap = len(self.advisoryparams)
782 if nbmp or nbap:
785 if nbmp or nbap:
783 msg.append(' (params:')
786 msg.append(' (params:')
784 if nbmp:
787 if nbmp:
785 msg.append(' %i mandatory' % nbmp)
788 msg.append(' %i mandatory' % nbmp)
786 if nbap:
789 if nbap:
787 msg.append(' %i advisory' % nbmp)
790 msg.append(' %i advisory' % nbmp)
788 msg.append(')')
791 msg.append(')')
789 if not self.data:
792 if not self.data:
790 msg.append(' empty payload')
793 msg.append(' empty payload')
791 elif util.safehasattr(self.data, 'next'):
794 elif util.safehasattr(self.data, 'next'):
792 msg.append(' streamed payload')
795 msg.append(' streamed payload')
793 else:
796 else:
794 msg.append(' %i bytes payload' % len(self.data))
797 msg.append(' %i bytes payload' % len(self.data))
795 msg.append('\n')
798 msg.append('\n')
796 ui.debug(''.join(msg))
799 ui.debug(''.join(msg))
797
800
798 #### header
801 #### header
799 if self.mandatory:
802 if self.mandatory:
800 parttype = self.type.upper()
803 parttype = self.type.upper()
801 else:
804 else:
802 parttype = self.type.lower()
805 parttype = self.type.lower()
803 outdebug(ui, 'part %s: "%s"' % (self.id, parttype))
806 outdebug(ui, 'part %s: "%s"' % (self.id, parttype))
804 ## parttype
807 ## parttype
805 header = [_pack(_fparttypesize, len(parttype)),
808 header = [_pack(_fparttypesize, len(parttype)),
806 parttype, _pack(_fpartid, self.id),
809 parttype, _pack(_fpartid, self.id),
807 ]
810 ]
808 ## parameters
811 ## parameters
809 # count
812 # count
810 manpar = self.mandatoryparams
813 manpar = self.mandatoryparams
811 advpar = self.advisoryparams
814 advpar = self.advisoryparams
812 header.append(_pack(_fpartparamcount, len(manpar), len(advpar)))
815 header.append(_pack(_fpartparamcount, len(manpar), len(advpar)))
813 # size
816 # size
814 parsizes = []
817 parsizes = []
815 for key, value in manpar:
818 for key, value in manpar:
816 parsizes.append(len(key))
819 parsizes.append(len(key))
817 parsizes.append(len(value))
820 parsizes.append(len(value))
818 for key, value in advpar:
821 for key, value in advpar:
819 parsizes.append(len(key))
822 parsizes.append(len(key))
820 parsizes.append(len(value))
823 parsizes.append(len(value))
821 paramsizes = _pack(_makefpartparamsizes(len(parsizes) / 2), *parsizes)
824 paramsizes = _pack(_makefpartparamsizes(len(parsizes) / 2), *parsizes)
822 header.append(paramsizes)
825 header.append(paramsizes)
823 # key, value
826 # key, value
824 for key, value in manpar:
827 for key, value in manpar:
825 header.append(key)
828 header.append(key)
826 header.append(value)
829 header.append(value)
827 for key, value in advpar:
830 for key, value in advpar:
828 header.append(key)
831 header.append(key)
829 header.append(value)
832 header.append(value)
830 ## finalize header
833 ## finalize header
831 headerchunk = ''.join(header)
834 headerchunk = ''.join(header)
832 outdebug(ui, 'header chunk size: %i' % len(headerchunk))
835 outdebug(ui, 'header chunk size: %i' % len(headerchunk))
833 yield _pack(_fpartheadersize, len(headerchunk))
836 yield _pack(_fpartheadersize, len(headerchunk))
834 yield headerchunk
837 yield headerchunk
835 ## payload
838 ## payload
836 try:
839 try:
837 for chunk in self._payloadchunks():
840 for chunk in self._payloadchunks():
838 outdebug(ui, 'payload chunk size: %i' % len(chunk))
841 outdebug(ui, 'payload chunk size: %i' % len(chunk))
839 yield _pack(_fpayloadsize, len(chunk))
842 yield _pack(_fpayloadsize, len(chunk))
840 yield chunk
843 yield chunk
841 except BaseException, exc:
844 except BaseException, exc:
842 # backup exception data for later
845 # backup exception data for later
843 ui.debug('bundle2-input-stream-interrupt: encoding exception %s'
846 ui.debug('bundle2-input-stream-interrupt: encoding exception %s'
844 % exc)
847 % exc)
845 exc_info = sys.exc_info()
848 exc_info = sys.exc_info()
846 msg = 'unexpected error: %s' % exc
849 msg = 'unexpected error: %s' % exc
847 interpart = bundlepart('error:abort', [('message', msg)],
850 interpart = bundlepart('error:abort', [('message', msg)],
848 mandatory=False)
851 mandatory=False)
849 interpart.id = 0
852 interpart.id = 0
850 yield _pack(_fpayloadsize, -1)
853 yield _pack(_fpayloadsize, -1)
851 for chunk in interpart.getchunks(ui=ui):
854 for chunk in interpart.getchunks(ui=ui):
852 yield chunk
855 yield chunk
853 outdebug(ui, 'closing payload chunk')
856 outdebug(ui, 'closing payload chunk')
854 # abort current part payload
857 # abort current part payload
855 yield _pack(_fpayloadsize, 0)
858 yield _pack(_fpayloadsize, 0)
856 raise exc_info[0], exc_info[1], exc_info[2]
859 raise exc_info[0], exc_info[1], exc_info[2]
857 # end of payload
860 # end of payload
858 outdebug(ui, 'closing payload chunk')
861 outdebug(ui, 'closing payload chunk')
859 yield _pack(_fpayloadsize, 0)
862 yield _pack(_fpayloadsize, 0)
860 self._generated = True
863 self._generated = True
861
864
862 def _payloadchunks(self):
865 def _payloadchunks(self):
863 """yield chunks of a the part payload
866 """yield chunks of a the part payload
864
867
865 Exists to handle the different methods to provide data to a part."""
868 Exists to handle the different methods to provide data to a part."""
866 # we only support fixed size data now.
869 # we only support fixed size data now.
867 # This will be improved in the future.
870 # This will be improved in the future.
868 if util.safehasattr(self.data, 'next'):
871 if util.safehasattr(self.data, 'next'):
869 buff = util.chunkbuffer(self.data)
872 buff = util.chunkbuffer(self.data)
870 chunk = buff.read(preferedchunksize)
873 chunk = buff.read(preferedchunksize)
871 while chunk:
874 while chunk:
872 yield chunk
875 yield chunk
873 chunk = buff.read(preferedchunksize)
876 chunk = buff.read(preferedchunksize)
874 elif len(self.data):
877 elif len(self.data):
875 yield self.data
878 yield self.data
876
879
877
880
878 flaginterrupt = -1
881 flaginterrupt = -1
879
882
880 class interrupthandler(unpackermixin):
883 class interrupthandler(unpackermixin):
881 """read one part and process it with restricted capability
884 """read one part and process it with restricted capability
882
885
883 This allows to transmit exception raised on the producer size during part
886 This allows to transmit exception raised on the producer size during part
884 iteration while the consumer is reading a part.
887 iteration while the consumer is reading a part.
885
888
886 Part processed in this manner only have access to a ui object,"""
889 Part processed in this manner only have access to a ui object,"""
887
890
888 def __init__(self, ui, fp):
891 def __init__(self, ui, fp):
889 super(interrupthandler, self).__init__(fp)
892 super(interrupthandler, self).__init__(fp)
890 self.ui = ui
893 self.ui = ui
891
894
892 def _readpartheader(self):
895 def _readpartheader(self):
893 """reads a part header size and return the bytes blob
896 """reads a part header size and return the bytes blob
894
897
895 returns None if empty"""
898 returns None if empty"""
896 headersize = self._unpack(_fpartheadersize)[0]
899 headersize = self._unpack(_fpartheadersize)[0]
897 if headersize < 0:
900 if headersize < 0:
898 raise error.BundleValueError('negative part header size: %i'
901 raise error.BundleValueError('negative part header size: %i'
899 % headersize)
902 % headersize)
900 indebug(self.ui, 'part header size: %i\n' % headersize)
903 indebug(self.ui, 'part header size: %i\n' % headersize)
901 if headersize:
904 if headersize:
902 return self._readexact(headersize)
905 return self._readexact(headersize)
903 return None
906 return None
904
907
905 def __call__(self):
908 def __call__(self):
906
909
907 self.ui.debug('bundle2-input-stream-interrupt:'
910 self.ui.debug('bundle2-input-stream-interrupt:'
908 ' opening out of band context\n')
911 ' opening out of band context\n')
909 indebug(self.ui, 'bundle2 stream interruption, looking for a part.')
912 indebug(self.ui, 'bundle2 stream interruption, looking for a part.')
910 headerblock = self._readpartheader()
913 headerblock = self._readpartheader()
911 if headerblock is None:
914 if headerblock is None:
912 indebug(self.ui, 'no part found during interruption.')
915 indebug(self.ui, 'no part found during interruption.')
913 return
916 return
914 part = unbundlepart(self.ui, headerblock, self._fp)
917 part = unbundlepart(self.ui, headerblock, self._fp)
915 op = interruptoperation(self.ui)
918 op = interruptoperation(self.ui)
916 _processpart(op, part)
919 _processpart(op, part)
917 self.ui.debug('bundle2-input-stream-interrupt:'
920 self.ui.debug('bundle2-input-stream-interrupt:'
918 ' closing out of band context\n')
921 ' closing out of band context\n')
919
922
920 class interruptoperation(object):
923 class interruptoperation(object):
921 """A limited operation to be use by part handler during interruption
924 """A limited operation to be use by part handler during interruption
922
925
923 It only have access to an ui object.
926 It only have access to an ui object.
924 """
927 """
925
928
926 def __init__(self, ui):
929 def __init__(self, ui):
927 self.ui = ui
930 self.ui = ui
928 self.reply = None
931 self.reply = None
929 self.captureoutput = False
932 self.captureoutput = False
930
933
931 @property
934 @property
932 def repo(self):
935 def repo(self):
933 raise RuntimeError('no repo access from stream interruption')
936 raise RuntimeError('no repo access from stream interruption')
934
937
935 def gettransaction(self):
938 def gettransaction(self):
936 raise TransactionUnavailable('no repo access from stream interruption')
939 raise TransactionUnavailable('no repo access from stream interruption')
937
940
938 class unbundlepart(unpackermixin):
941 class unbundlepart(unpackermixin):
939 """a bundle part read from a bundle"""
942 """a bundle part read from a bundle"""
940
943
941 def __init__(self, ui, header, fp):
944 def __init__(self, ui, header, fp):
942 super(unbundlepart, self).__init__(fp)
945 super(unbundlepart, self).__init__(fp)
943 self.ui = ui
946 self.ui = ui
944 # unbundle state attr
947 # unbundle state attr
945 self._headerdata = header
948 self._headerdata = header
946 self._headeroffset = 0
949 self._headeroffset = 0
947 self._initialized = False
950 self._initialized = False
948 self.consumed = False
951 self.consumed = False
949 # part data
952 # part data
950 self.id = None
953 self.id = None
951 self.type = None
954 self.type = None
952 self.mandatoryparams = None
955 self.mandatoryparams = None
953 self.advisoryparams = None
956 self.advisoryparams = None
954 self.params = None
957 self.params = None
955 self.mandatorykeys = ()
958 self.mandatorykeys = ()
956 self._payloadstream = None
959 self._payloadstream = None
957 self._readheader()
960 self._readheader()
958 self._mandatory = None
961 self._mandatory = None
959 self._chunkindex = [] #(payload, file) position tuples for chunk starts
962 self._chunkindex = [] #(payload, file) position tuples for chunk starts
960 self._pos = 0
963 self._pos = 0
961
964
962 def _fromheader(self, size):
965 def _fromheader(self, size):
963 """return the next <size> byte from the header"""
966 """return the next <size> byte from the header"""
964 offset = self._headeroffset
967 offset = self._headeroffset
965 data = self._headerdata[offset:(offset + size)]
968 data = self._headerdata[offset:(offset + size)]
966 self._headeroffset = offset + size
969 self._headeroffset = offset + size
967 return data
970 return data
968
971
969 def _unpackheader(self, format):
972 def _unpackheader(self, format):
970 """read given format from header
973 """read given format from header
971
974
972 This automatically compute the size of the format to read."""
975 This automatically compute the size of the format to read."""
973 data = self._fromheader(struct.calcsize(format))
976 data = self._fromheader(struct.calcsize(format))
974 return _unpack(format, data)
977 return _unpack(format, data)
975
978
976 def _initparams(self, mandatoryparams, advisoryparams):
979 def _initparams(self, mandatoryparams, advisoryparams):
977 """internal function to setup all logic related parameters"""
980 """internal function to setup all logic related parameters"""
978 # make it read only to prevent people touching it by mistake.
981 # make it read only to prevent people touching it by mistake.
979 self.mandatoryparams = tuple(mandatoryparams)
982 self.mandatoryparams = tuple(mandatoryparams)
980 self.advisoryparams = tuple(advisoryparams)
983 self.advisoryparams = tuple(advisoryparams)
981 # user friendly UI
984 # user friendly UI
982 self.params = dict(self.mandatoryparams)
985 self.params = dict(self.mandatoryparams)
983 self.params.update(dict(self.advisoryparams))
986 self.params.update(dict(self.advisoryparams))
984 self.mandatorykeys = frozenset(p[0] for p in mandatoryparams)
987 self.mandatorykeys = frozenset(p[0] for p in mandatoryparams)
985
988
986 def _payloadchunks(self, chunknum=0):
989 def _payloadchunks(self, chunknum=0):
987 '''seek to specified chunk and start yielding data'''
990 '''seek to specified chunk and start yielding data'''
988 if len(self._chunkindex) == 0:
991 if len(self._chunkindex) == 0:
989 assert chunknum == 0, 'Must start with chunk 0'
992 assert chunknum == 0, 'Must start with chunk 0'
990 self._chunkindex.append((0, super(unbundlepart, self).tell()))
993 self._chunkindex.append((0, super(unbundlepart, self).tell()))
991 else:
994 else:
992 assert chunknum < len(self._chunkindex), \
995 assert chunknum < len(self._chunkindex), \
993 'Unknown chunk %d' % chunknum
996 'Unknown chunk %d' % chunknum
994 super(unbundlepart, self).seek(self._chunkindex[chunknum][1])
997 super(unbundlepart, self).seek(self._chunkindex[chunknum][1])
995
998
996 pos = self._chunkindex[chunknum][0]
999 pos = self._chunkindex[chunknum][0]
997 payloadsize = self._unpack(_fpayloadsize)[0]
1000 payloadsize = self._unpack(_fpayloadsize)[0]
998 indebug(self.ui, 'payload chunk size: %i' % payloadsize)
1001 indebug(self.ui, 'payload chunk size: %i' % payloadsize)
999 while payloadsize:
1002 while payloadsize:
1000 if payloadsize == flaginterrupt:
1003 if payloadsize == flaginterrupt:
1001 # interruption detection, the handler will now read a
1004 # interruption detection, the handler will now read a
1002 # single part and process it.
1005 # single part and process it.
1003 interrupthandler(self.ui, self._fp)()
1006 interrupthandler(self.ui, self._fp)()
1004 elif payloadsize < 0:
1007 elif payloadsize < 0:
1005 msg = 'negative payload chunk size: %i' % payloadsize
1008 msg = 'negative payload chunk size: %i' % payloadsize
1006 raise error.BundleValueError(msg)
1009 raise error.BundleValueError(msg)
1007 else:
1010 else:
1008 result = self._readexact(payloadsize)
1011 result = self._readexact(payloadsize)
1009 chunknum += 1
1012 chunknum += 1
1010 pos += payloadsize
1013 pos += payloadsize
1011 if chunknum == len(self._chunkindex):
1014 if chunknum == len(self._chunkindex):
1012 self._chunkindex.append((pos,
1015 self._chunkindex.append((pos,
1013 super(unbundlepart, self).tell()))
1016 super(unbundlepart, self).tell()))
1014 yield result
1017 yield result
1015 payloadsize = self._unpack(_fpayloadsize)[0]
1018 payloadsize = self._unpack(_fpayloadsize)[0]
1016 indebug(self.ui, 'payload chunk size: %i' % payloadsize)
1019 indebug(self.ui, 'payload chunk size: %i' % payloadsize)
1017
1020
1018 def _findchunk(self, pos):
1021 def _findchunk(self, pos):
1019 '''for a given payload position, return a chunk number and offset'''
1022 '''for a given payload position, return a chunk number and offset'''
1020 for chunk, (ppos, fpos) in enumerate(self._chunkindex):
1023 for chunk, (ppos, fpos) in enumerate(self._chunkindex):
1021 if ppos == pos:
1024 if ppos == pos:
1022 return chunk, 0
1025 return chunk, 0
1023 elif ppos > pos:
1026 elif ppos > pos:
1024 return chunk - 1, pos - self._chunkindex[chunk - 1][0]
1027 return chunk - 1, pos - self._chunkindex[chunk - 1][0]
1025 raise ValueError('Unknown chunk')
1028 raise ValueError('Unknown chunk')
1026
1029
1027 def _readheader(self):
1030 def _readheader(self):
1028 """read the header and setup the object"""
1031 """read the header and setup the object"""
1029 typesize = self._unpackheader(_fparttypesize)[0]
1032 typesize = self._unpackheader(_fparttypesize)[0]
1030 self.type = self._fromheader(typesize)
1033 self.type = self._fromheader(typesize)
1031 indebug(self.ui, 'part type: "%s"' % self.type)
1034 indebug(self.ui, 'part type: "%s"' % self.type)
1032 self.id = self._unpackheader(_fpartid)[0]
1035 self.id = self._unpackheader(_fpartid)[0]
1033 indebug(self.ui, 'part id: "%s"' % self.id)
1036 indebug(self.ui, 'part id: "%s"' % self.id)
1034 # extract mandatory bit from type
1037 # extract mandatory bit from type
1035 self.mandatory = (self.type != self.type.lower())
1038 self.mandatory = (self.type != self.type.lower())
1036 self.type = self.type.lower()
1039 self.type = self.type.lower()
1037 ## reading parameters
1040 ## reading parameters
1038 # param count
1041 # param count
1039 mancount, advcount = self._unpackheader(_fpartparamcount)
1042 mancount, advcount = self._unpackheader(_fpartparamcount)
1040 indebug(self.ui, 'part parameters: %i' % (mancount + advcount))
1043 indebug(self.ui, 'part parameters: %i' % (mancount + advcount))
1041 # param size
1044 # param size
1042 fparamsizes = _makefpartparamsizes(mancount + advcount)
1045 fparamsizes = _makefpartparamsizes(mancount + advcount)
1043 paramsizes = self._unpackheader(fparamsizes)
1046 paramsizes = self._unpackheader(fparamsizes)
1044 # make it a list of couple again
1047 # make it a list of couple again
1045 paramsizes = zip(paramsizes[::2], paramsizes[1::2])
1048 paramsizes = zip(paramsizes[::2], paramsizes[1::2])
1046 # split mandatory from advisory
1049 # split mandatory from advisory
1047 mansizes = paramsizes[:mancount]
1050 mansizes = paramsizes[:mancount]
1048 advsizes = paramsizes[mancount:]
1051 advsizes = paramsizes[mancount:]
1049 # retrieve param value
1052 # retrieve param value
1050 manparams = []
1053 manparams = []
1051 for key, value in mansizes:
1054 for key, value in mansizes:
1052 manparams.append((self._fromheader(key), self._fromheader(value)))
1055 manparams.append((self._fromheader(key), self._fromheader(value)))
1053 advparams = []
1056 advparams = []
1054 for key, value in advsizes:
1057 for key, value in advsizes:
1055 advparams.append((self._fromheader(key), self._fromheader(value)))
1058 advparams.append((self._fromheader(key), self._fromheader(value)))
1056 self._initparams(manparams, advparams)
1059 self._initparams(manparams, advparams)
1057 ## part payload
1060 ## part payload
1058 self._payloadstream = util.chunkbuffer(self._payloadchunks())
1061 self._payloadstream = util.chunkbuffer(self._payloadchunks())
1059 # we read the data, tell it
1062 # we read the data, tell it
1060 self._initialized = True
1063 self._initialized = True
1061
1064
1062 def read(self, size=None):
1065 def read(self, size=None):
1063 """read payload data"""
1066 """read payload data"""
1064 if not self._initialized:
1067 if not self._initialized:
1065 self._readheader()
1068 self._readheader()
1066 if size is None:
1069 if size is None:
1067 data = self._payloadstream.read()
1070 data = self._payloadstream.read()
1068 else:
1071 else:
1069 data = self._payloadstream.read(size)
1072 data = self._payloadstream.read(size)
1070 self._pos += len(data)
1073 self._pos += len(data)
1071 if size is None or len(data) < size:
1074 if size is None or len(data) < size:
1072 if not self.consumed and self._pos:
1075 if not self.consumed and self._pos:
1073 self.ui.debug('bundle2-input-part: total payload size %i\n'
1076 self.ui.debug('bundle2-input-part: total payload size %i\n'
1074 % self._pos)
1077 % self._pos)
1075 self.consumed = True
1078 self.consumed = True
1076 return data
1079 return data
1077
1080
1078 def tell(self):
1081 def tell(self):
1079 return self._pos
1082 return self._pos
1080
1083
1081 def seek(self, offset, whence=0):
1084 def seek(self, offset, whence=0):
1082 if whence == 0:
1085 if whence == 0:
1083 newpos = offset
1086 newpos = offset
1084 elif whence == 1:
1087 elif whence == 1:
1085 newpos = self._pos + offset
1088 newpos = self._pos + offset
1086 elif whence == 2:
1089 elif whence == 2:
1087 if not self.consumed:
1090 if not self.consumed:
1088 self.read()
1091 self.read()
1089 newpos = self._chunkindex[-1][0] - offset
1092 newpos = self._chunkindex[-1][0] - offset
1090 else:
1093 else:
1091 raise ValueError('Unknown whence value: %r' % (whence,))
1094 raise ValueError('Unknown whence value: %r' % (whence,))
1092
1095
1093 if newpos > self._chunkindex[-1][0] and not self.consumed:
1096 if newpos > self._chunkindex[-1][0] and not self.consumed:
1094 self.read()
1097 self.read()
1095 if not 0 <= newpos <= self._chunkindex[-1][0]:
1098 if not 0 <= newpos <= self._chunkindex[-1][0]:
1096 raise ValueError('Offset out of range')
1099 raise ValueError('Offset out of range')
1097
1100
1098 if self._pos != newpos:
1101 if self._pos != newpos:
1099 chunk, internaloffset = self._findchunk(newpos)
1102 chunk, internaloffset = self._findchunk(newpos)
1100 self._payloadstream = util.chunkbuffer(self._payloadchunks(chunk))
1103 self._payloadstream = util.chunkbuffer(self._payloadchunks(chunk))
1101 adjust = self.read(internaloffset)
1104 adjust = self.read(internaloffset)
1102 if len(adjust) != internaloffset:
1105 if len(adjust) != internaloffset:
1103 raise util.Abort(_('Seek failed\n'))
1106 raise util.Abort(_('Seek failed\n'))
1104 self._pos = newpos
1107 self._pos = newpos
1105
1108
1106 # These are only the static capabilities.
1109 # These are only the static capabilities.
1107 # Check the 'getrepocaps' function for the rest.
1110 # Check the 'getrepocaps' function for the rest.
1108 capabilities = {'HG20': (),
1111 capabilities = {'HG20': (),
1109 'error': ('abort', 'unsupportedcontent', 'pushraced'),
1112 'error': ('abort', 'unsupportedcontent', 'pushraced'),
1110 'listkeys': (),
1113 'listkeys': (),
1111 'pushkey': (),
1114 'pushkey': (),
1112 'digests': tuple(sorted(util.DIGESTS.keys())),
1115 'digests': tuple(sorted(util.DIGESTS.keys())),
1113 'remote-changegroup': ('http', 'https'),
1116 'remote-changegroup': ('http', 'https'),
1114 'hgtagsfnodes': (),
1117 'hgtagsfnodes': (),
1115 }
1118 }
1116
1119
1117 def getrepocaps(repo, allowpushback=False):
1120 def getrepocaps(repo, allowpushback=False):
1118 """return the bundle2 capabilities for a given repo
1121 """return the bundle2 capabilities for a given repo
1119
1122
1120 Exists to allow extensions (like evolution) to mutate the capabilities.
1123 Exists to allow extensions (like evolution) to mutate the capabilities.
1121 """
1124 """
1122 caps = capabilities.copy()
1125 caps = capabilities.copy()
1123 caps['changegroup'] = tuple(sorted(changegroup.packermap.keys()))
1126 caps['changegroup'] = tuple(sorted(changegroup.packermap.keys()))
1124 if obsolete.isenabled(repo, obsolete.exchangeopt):
1127 if obsolete.isenabled(repo, obsolete.exchangeopt):
1125 supportedformat = tuple('V%i' % v for v in obsolete.formats)
1128 supportedformat = tuple('V%i' % v for v in obsolete.formats)
1126 caps['obsmarkers'] = supportedformat
1129 caps['obsmarkers'] = supportedformat
1127 if allowpushback:
1130 if allowpushback:
1128 caps['pushback'] = ()
1131 caps['pushback'] = ()
1129 return caps
1132 return caps
1130
1133
1131 def bundle2caps(remote):
1134 def bundle2caps(remote):
1132 """return the bundle capabilities of a peer as dict"""
1135 """return the bundle capabilities of a peer as dict"""
1133 raw = remote.capable('bundle2')
1136 raw = remote.capable('bundle2')
1134 if not raw and raw != '':
1137 if not raw and raw != '':
1135 return {}
1138 return {}
1136 capsblob = urllib.unquote(remote.capable('bundle2'))
1139 capsblob = urllib.unquote(remote.capable('bundle2'))
1137 return decodecaps(capsblob)
1140 return decodecaps(capsblob)
1138
1141
1139 def obsmarkersversion(caps):
1142 def obsmarkersversion(caps):
1140 """extract the list of supported obsmarkers versions from a bundle2caps dict
1143 """extract the list of supported obsmarkers versions from a bundle2caps dict
1141 """
1144 """
1142 obscaps = caps.get('obsmarkers', ())
1145 obscaps = caps.get('obsmarkers', ())
1143 return [int(c[1:]) for c in obscaps if c.startswith('V')]
1146 return [int(c[1:]) for c in obscaps if c.startswith('V')]
1144
1147
1145 @parthandler('changegroup', ('version',))
1148 @parthandler('changegroup', ('version',))
1146 def handlechangegroup(op, inpart):
1149 def handlechangegroup(op, inpart):
1147 """apply a changegroup part on the repo
1150 """apply a changegroup part on the repo
1148
1151
1149 This is a very early implementation that will massive rework before being
1152 This is a very early implementation that will massive rework before being
1150 inflicted to any end-user.
1153 inflicted to any end-user.
1151 """
1154 """
1152 # Make sure we trigger a transaction creation
1155 # Make sure we trigger a transaction creation
1153 #
1156 #
1154 # The addchangegroup function will get a transaction object by itself, but
1157 # The addchangegroup function will get a transaction object by itself, but
1155 # we need to make sure we trigger the creation of a transaction object used
1158 # we need to make sure we trigger the creation of a transaction object used
1156 # for the whole processing scope.
1159 # for the whole processing scope.
1157 op.gettransaction()
1160 op.gettransaction()
1158 unpackerversion = inpart.params.get('version', '01')
1161 unpackerversion = inpart.params.get('version', '01')
1159 # We should raise an appropriate exception here
1162 # We should raise an appropriate exception here
1160 unpacker = changegroup.packermap[unpackerversion][1]
1163 unpacker = changegroup.packermap[unpackerversion][1]
1161 cg = unpacker(inpart, 'UN')
1164 cg = unpacker(inpart, 'UN')
1162 # the source and url passed here are overwritten by the one contained in
1165 # the source and url passed here are overwritten by the one contained in
1163 # the transaction.hookargs argument. So 'bundle2' is a placeholder
1166 # the transaction.hookargs argument. So 'bundle2' is a placeholder
1164 ret = changegroup.addchangegroup(op.repo, cg, 'bundle2', 'bundle2')
1167 ret = changegroup.addchangegroup(op.repo, cg, 'bundle2', 'bundle2')
1165 op.records.add('changegroup', {'return': ret})
1168 op.records.add('changegroup', {'return': ret})
1166 if op.reply is not None:
1169 if op.reply is not None:
1167 # This is definitely not the final form of this
1170 # This is definitely not the final form of this
1168 # return. But one need to start somewhere.
1171 # return. But one need to start somewhere.
1169 part = op.reply.newpart('reply:changegroup', mandatory=False)
1172 part = op.reply.newpart('reply:changegroup', mandatory=False)
1170 part.addparam('in-reply-to', str(inpart.id), mandatory=False)
1173 part.addparam('in-reply-to', str(inpart.id), mandatory=False)
1171 part.addparam('return', '%i' % ret, mandatory=False)
1174 part.addparam('return', '%i' % ret, mandatory=False)
1172 assert not inpart.read()
1175 assert not inpart.read()
1173
1176
1174 _remotechangegroupparams = tuple(['url', 'size', 'digests'] +
1177 _remotechangegroupparams = tuple(['url', 'size', 'digests'] +
1175 ['digest:%s' % k for k in util.DIGESTS.keys()])
1178 ['digest:%s' % k for k in util.DIGESTS.keys()])
1176 @parthandler('remote-changegroup', _remotechangegroupparams)
1179 @parthandler('remote-changegroup', _remotechangegroupparams)
1177 def handleremotechangegroup(op, inpart):
1180 def handleremotechangegroup(op, inpart):
1178 """apply a bundle10 on the repo, given an url and validation information
1181 """apply a bundle10 on the repo, given an url and validation information
1179
1182
1180 All the information about the remote bundle to import are given as
1183 All the information about the remote bundle to import are given as
1181 parameters. The parameters include:
1184 parameters. The parameters include:
1182 - url: the url to the bundle10.
1185 - url: the url to the bundle10.
1183 - size: the bundle10 file size. It is used to validate what was
1186 - size: the bundle10 file size. It is used to validate what was
1184 retrieved by the client matches the server knowledge about the bundle.
1187 retrieved by the client matches the server knowledge about the bundle.
1185 - digests: a space separated list of the digest types provided as
1188 - digests: a space separated list of the digest types provided as
1186 parameters.
1189 parameters.
1187 - digest:<digest-type>: the hexadecimal representation of the digest with
1190 - digest:<digest-type>: the hexadecimal representation of the digest with
1188 that name. Like the size, it is used to validate what was retrieved by
1191 that name. Like the size, it is used to validate what was retrieved by
1189 the client matches what the server knows about the bundle.
1192 the client matches what the server knows about the bundle.
1190
1193
1191 When multiple digest types are given, all of them are checked.
1194 When multiple digest types are given, all of them are checked.
1192 """
1195 """
1193 try:
1196 try:
1194 raw_url = inpart.params['url']
1197 raw_url = inpart.params['url']
1195 except KeyError:
1198 except KeyError:
1196 raise util.Abort(_('remote-changegroup: missing "%s" param') % 'url')
1199 raise util.Abort(_('remote-changegroup: missing "%s" param') % 'url')
1197 parsed_url = util.url(raw_url)
1200 parsed_url = util.url(raw_url)
1198 if parsed_url.scheme not in capabilities['remote-changegroup']:
1201 if parsed_url.scheme not in capabilities['remote-changegroup']:
1199 raise util.Abort(_('remote-changegroup does not support %s urls') %
1202 raise util.Abort(_('remote-changegroup does not support %s urls') %
1200 parsed_url.scheme)
1203 parsed_url.scheme)
1201
1204
1202 try:
1205 try:
1203 size = int(inpart.params['size'])
1206 size = int(inpart.params['size'])
1204 except ValueError:
1207 except ValueError:
1205 raise util.Abort(_('remote-changegroup: invalid value for param "%s"')
1208 raise util.Abort(_('remote-changegroup: invalid value for param "%s"')
1206 % 'size')
1209 % 'size')
1207 except KeyError:
1210 except KeyError:
1208 raise util.Abort(_('remote-changegroup: missing "%s" param') % 'size')
1211 raise util.Abort(_('remote-changegroup: missing "%s" param') % 'size')
1209
1212
1210 digests = {}
1213 digests = {}
1211 for typ in inpart.params.get('digests', '').split():
1214 for typ in inpart.params.get('digests', '').split():
1212 param = 'digest:%s' % typ
1215 param = 'digest:%s' % typ
1213 try:
1216 try:
1214 value = inpart.params[param]
1217 value = inpart.params[param]
1215 except KeyError:
1218 except KeyError:
1216 raise util.Abort(_('remote-changegroup: missing "%s" param') %
1219 raise util.Abort(_('remote-changegroup: missing "%s" param') %
1217 param)
1220 param)
1218 digests[typ] = value
1221 digests[typ] = value
1219
1222
1220 real_part = util.digestchecker(url.open(op.ui, raw_url), size, digests)
1223 real_part = util.digestchecker(url.open(op.ui, raw_url), size, digests)
1221
1224
1222 # Make sure we trigger a transaction creation
1225 # Make sure we trigger a transaction creation
1223 #
1226 #
1224 # The addchangegroup function will get a transaction object by itself, but
1227 # The addchangegroup function will get a transaction object by itself, but
1225 # we need to make sure we trigger the creation of a transaction object used
1228 # we need to make sure we trigger the creation of a transaction object used
1226 # for the whole processing scope.
1229 # for the whole processing scope.
1227 op.gettransaction()
1230 op.gettransaction()
1228 import exchange
1231 import exchange
1229 cg = exchange.readbundle(op.repo.ui, real_part, raw_url)
1232 cg = exchange.readbundle(op.repo.ui, real_part, raw_url)
1230 if not isinstance(cg, changegroup.cg1unpacker):
1233 if not isinstance(cg, changegroup.cg1unpacker):
1231 raise util.Abort(_('%s: not a bundle version 1.0') %
1234 raise util.Abort(_('%s: not a bundle version 1.0') %
1232 util.hidepassword(raw_url))
1235 util.hidepassword(raw_url))
1233 ret = changegroup.addchangegroup(op.repo, cg, 'bundle2', 'bundle2')
1236 ret = changegroup.addchangegroup(op.repo, cg, 'bundle2', 'bundle2')
1234 op.records.add('changegroup', {'return': ret})
1237 op.records.add('changegroup', {'return': ret})
1235 if op.reply is not None:
1238 if op.reply is not None:
1236 # This is definitely not the final form of this
1239 # This is definitely not the final form of this
1237 # return. But one need to start somewhere.
1240 # return. But one need to start somewhere.
1238 part = op.reply.newpart('reply:changegroup')
1241 part = op.reply.newpart('reply:changegroup')
1239 part.addparam('in-reply-to', str(inpart.id), mandatory=False)
1242 part.addparam('in-reply-to', str(inpart.id), mandatory=False)
1240 part.addparam('return', '%i' % ret, mandatory=False)
1243 part.addparam('return', '%i' % ret, mandatory=False)
1241 try:
1244 try:
1242 real_part.validate()
1245 real_part.validate()
1243 except util.Abort, e:
1246 except util.Abort, e:
1244 raise util.Abort(_('bundle at %s is corrupted:\n%s') %
1247 raise util.Abort(_('bundle at %s is corrupted:\n%s') %
1245 (util.hidepassword(raw_url), str(e)))
1248 (util.hidepassword(raw_url), str(e)))
1246 assert not inpart.read()
1249 assert not inpart.read()
1247
1250
1248 @parthandler('reply:changegroup', ('return', 'in-reply-to'))
1251 @parthandler('reply:changegroup', ('return', 'in-reply-to'))
1249 def handlereplychangegroup(op, inpart):
1252 def handlereplychangegroup(op, inpart):
1250 ret = int(inpart.params['return'])
1253 ret = int(inpart.params['return'])
1251 replyto = int(inpart.params['in-reply-to'])
1254 replyto = int(inpart.params['in-reply-to'])
1252 op.records.add('changegroup', {'return': ret}, replyto)
1255 op.records.add('changegroup', {'return': ret}, replyto)
1253
1256
1254 @parthandler('check:heads')
1257 @parthandler('check:heads')
1255 def handlecheckheads(op, inpart):
1258 def handlecheckheads(op, inpart):
1256 """check that head of the repo did not change
1259 """check that head of the repo did not change
1257
1260
1258 This is used to detect a push race when using unbundle.
1261 This is used to detect a push race when using unbundle.
1259 This replaces the "heads" argument of unbundle."""
1262 This replaces the "heads" argument of unbundle."""
1260 h = inpart.read(20)
1263 h = inpart.read(20)
1261 heads = []
1264 heads = []
1262 while len(h) == 20:
1265 while len(h) == 20:
1263 heads.append(h)
1266 heads.append(h)
1264 h = inpart.read(20)
1267 h = inpart.read(20)
1265 assert not h
1268 assert not h
1266 if heads != op.repo.heads():
1269 if heads != op.repo.heads():
1267 raise error.PushRaced('repository changed while pushing - '
1270 raise error.PushRaced('repository changed while pushing - '
1268 'please try again')
1271 'please try again')
1269
1272
1270 @parthandler('output')
1273 @parthandler('output')
1271 def handleoutput(op, inpart):
1274 def handleoutput(op, inpart):
1272 """forward output captured on the server to the client"""
1275 """forward output captured on the server to the client"""
1273 for line in inpart.read().splitlines():
1276 for line in inpart.read().splitlines():
1274 op.ui.status(('remote: %s\n' % line))
1277 op.ui.status(('remote: %s\n' % line))
1275
1278
1276 @parthandler('replycaps')
1279 @parthandler('replycaps')
1277 def handlereplycaps(op, inpart):
1280 def handlereplycaps(op, inpart):
1278 """Notify that a reply bundle should be created
1281 """Notify that a reply bundle should be created
1279
1282
1280 The payload contains the capabilities information for the reply"""
1283 The payload contains the capabilities information for the reply"""
1281 caps = decodecaps(inpart.read())
1284 caps = decodecaps(inpart.read())
1282 if op.reply is None:
1285 if op.reply is None:
1283 op.reply = bundle20(op.ui, caps)
1286 op.reply = bundle20(op.ui, caps)
1284
1287
1285 @parthandler('error:abort', ('message', 'hint'))
1288 @parthandler('error:abort', ('message', 'hint'))
1286 def handleerrorabort(op, inpart):
1289 def handleerrorabort(op, inpart):
1287 """Used to transmit abort error over the wire"""
1290 """Used to transmit abort error over the wire"""
1288 raise util.Abort(inpart.params['message'], hint=inpart.params.get('hint'))
1291 raise util.Abort(inpart.params['message'], hint=inpart.params.get('hint'))
1289
1292
1290 @parthandler('error:unsupportedcontent', ('parttype', 'params'))
1293 @parthandler('error:unsupportedcontent', ('parttype', 'params'))
1291 def handleerrorunsupportedcontent(op, inpart):
1294 def handleerrorunsupportedcontent(op, inpart):
1292 """Used to transmit unknown content error over the wire"""
1295 """Used to transmit unknown content error over the wire"""
1293 kwargs = {}
1296 kwargs = {}
1294 parttype = inpart.params.get('parttype')
1297 parttype = inpart.params.get('parttype')
1295 if parttype is not None:
1298 if parttype is not None:
1296 kwargs['parttype'] = parttype
1299 kwargs['parttype'] = parttype
1297 params = inpart.params.get('params')
1300 params = inpart.params.get('params')
1298 if params is not None:
1301 if params is not None:
1299 kwargs['params'] = params.split('\0')
1302 kwargs['params'] = params.split('\0')
1300
1303
1301 raise error.UnsupportedPartError(**kwargs)
1304 raise error.UnsupportedPartError(**kwargs)
1302
1305
1303 @parthandler('error:pushraced', ('message',))
1306 @parthandler('error:pushraced', ('message',))
1304 def handleerrorpushraced(op, inpart):
1307 def handleerrorpushraced(op, inpart):
1305 """Used to transmit push race error over the wire"""
1308 """Used to transmit push race error over the wire"""
1306 raise error.ResponseError(_('push failed:'), inpart.params['message'])
1309 raise error.ResponseError(_('push failed:'), inpart.params['message'])
1307
1310
1308 @parthandler('listkeys', ('namespace',))
1311 @parthandler('listkeys', ('namespace',))
1309 def handlelistkeys(op, inpart):
1312 def handlelistkeys(op, inpart):
1310 """retrieve pushkey namespace content stored in a bundle2"""
1313 """retrieve pushkey namespace content stored in a bundle2"""
1311 namespace = inpart.params['namespace']
1314 namespace = inpart.params['namespace']
1312 r = pushkey.decodekeys(inpart.read())
1315 r = pushkey.decodekeys(inpart.read())
1313 op.records.add('listkeys', (namespace, r))
1316 op.records.add('listkeys', (namespace, r))
1314
1317
1315 @parthandler('pushkey', ('namespace', 'key', 'old', 'new'))
1318 @parthandler('pushkey', ('namespace', 'key', 'old', 'new'))
1316 def handlepushkey(op, inpart):
1319 def handlepushkey(op, inpart):
1317 """process a pushkey request"""
1320 """process a pushkey request"""
1318 dec = pushkey.decode
1321 dec = pushkey.decode
1319 namespace = dec(inpart.params['namespace'])
1322 namespace = dec(inpart.params['namespace'])
1320 key = dec(inpart.params['key'])
1323 key = dec(inpart.params['key'])
1321 old = dec(inpart.params['old'])
1324 old = dec(inpart.params['old'])
1322 new = dec(inpart.params['new'])
1325 new = dec(inpart.params['new'])
1323 ret = op.repo.pushkey(namespace, key, old, new)
1326 ret = op.repo.pushkey(namespace, key, old, new)
1324 record = {'namespace': namespace,
1327 record = {'namespace': namespace,
1325 'key': key,
1328 'key': key,
1326 'old': old,
1329 'old': old,
1327 'new': new}
1330 'new': new}
1328 op.records.add('pushkey', record)
1331 op.records.add('pushkey', record)
1329 if op.reply is not None:
1332 if op.reply is not None:
1330 rpart = op.reply.newpart('reply:pushkey')
1333 rpart = op.reply.newpart('reply:pushkey')
1331 rpart.addparam('in-reply-to', str(inpart.id), mandatory=False)
1334 rpart.addparam('in-reply-to', str(inpart.id), mandatory=False)
1332 rpart.addparam('return', '%i' % ret, mandatory=False)
1335 rpart.addparam('return', '%i' % ret, mandatory=False)
1333 if inpart.mandatory and not ret:
1336 if inpart.mandatory and not ret:
1334 kwargs = {}
1337 kwargs = {}
1335 for key in ('namespace', 'key', 'new', 'old', 'ret'):
1338 for key in ('namespace', 'key', 'new', 'old', 'ret'):
1336 if key in inpart.params:
1339 if key in inpart.params:
1337 kwargs[key] = inpart.params[key]
1340 kwargs[key] = inpart.params[key]
1338 raise error.PushkeyFailed(partid=str(inpart.id), **kwargs)
1341 raise error.PushkeyFailed(partid=str(inpart.id), **kwargs)
1339
1342
1340 @parthandler('reply:pushkey', ('return', 'in-reply-to'))
1343 @parthandler('reply:pushkey', ('return', 'in-reply-to'))
1341 def handlepushkeyreply(op, inpart):
1344 def handlepushkeyreply(op, inpart):
1342 """retrieve the result of a pushkey request"""
1345 """retrieve the result of a pushkey request"""
1343 ret = int(inpart.params['return'])
1346 ret = int(inpart.params['return'])
1344 partid = int(inpart.params['in-reply-to'])
1347 partid = int(inpart.params['in-reply-to'])
1345 op.records.add('pushkey', {'return': ret}, partid)
1348 op.records.add('pushkey', {'return': ret}, partid)
1346
1349
1347 @parthandler('obsmarkers')
1350 @parthandler('obsmarkers')
1348 def handleobsmarker(op, inpart):
1351 def handleobsmarker(op, inpart):
1349 """add a stream of obsmarkers to the repo"""
1352 """add a stream of obsmarkers to the repo"""
1350 tr = op.gettransaction()
1353 tr = op.gettransaction()
1351 markerdata = inpart.read()
1354 markerdata = inpart.read()
1352 if op.ui.config('experimental', 'obsmarkers-exchange-debug', False):
1355 if op.ui.config('experimental', 'obsmarkers-exchange-debug', False):
1353 op.ui.write(('obsmarker-exchange: %i bytes received\n')
1356 op.ui.write(('obsmarker-exchange: %i bytes received\n')
1354 % len(markerdata))
1357 % len(markerdata))
1355 new = op.repo.obsstore.mergemarkers(tr, markerdata)
1358 new = op.repo.obsstore.mergemarkers(tr, markerdata)
1356 if new:
1359 if new:
1357 op.repo.ui.status(_('%i new obsolescence markers\n') % new)
1360 op.repo.ui.status(_('%i new obsolescence markers\n') % new)
1358 op.records.add('obsmarkers', {'new': new})
1361 op.records.add('obsmarkers', {'new': new})
1359 if op.reply is not None:
1362 if op.reply is not None:
1360 rpart = op.reply.newpart('reply:obsmarkers')
1363 rpart = op.reply.newpart('reply:obsmarkers')
1361 rpart.addparam('in-reply-to', str(inpart.id), mandatory=False)
1364 rpart.addparam('in-reply-to', str(inpart.id), mandatory=False)
1362 rpart.addparam('new', '%i' % new, mandatory=False)
1365 rpart.addparam('new', '%i' % new, mandatory=False)
1363
1366
1364
1367
1365 @parthandler('reply:obsmarkers', ('new', 'in-reply-to'))
1368 @parthandler('reply:obsmarkers', ('new', 'in-reply-to'))
1366 def handlepushkeyreply(op, inpart):
1369 def handlepushkeyreply(op, inpart):
1367 """retrieve the result of a pushkey request"""
1370 """retrieve the result of a pushkey request"""
1368 ret = int(inpart.params['new'])
1371 ret = int(inpart.params['new'])
1369 partid = int(inpart.params['in-reply-to'])
1372 partid = int(inpart.params['in-reply-to'])
1370 op.records.add('obsmarkers', {'new': ret}, partid)
1373 op.records.add('obsmarkers', {'new': ret}, partid)
1371
1374
1372 @parthandler('hgtagsfnodes')
1375 @parthandler('hgtagsfnodes')
1373 def handlehgtagsfnodes(op, inpart):
1376 def handlehgtagsfnodes(op, inpart):
1374 """Applies .hgtags fnodes cache entries to the local repo.
1377 """Applies .hgtags fnodes cache entries to the local repo.
1375
1378
1376 Payload is pairs of 20 byte changeset nodes and filenodes.
1379 Payload is pairs of 20 byte changeset nodes and filenodes.
1377 """
1380 """
1378 cache = tags.hgtagsfnodescache(op.repo.unfiltered())
1381 cache = tags.hgtagsfnodescache(op.repo.unfiltered())
1379
1382
1380 count = 0
1383 count = 0
1381 while True:
1384 while True:
1382 node = inpart.read(20)
1385 node = inpart.read(20)
1383 fnode = inpart.read(20)
1386 fnode = inpart.read(20)
1384 if len(node) < 20 or len(fnode) < 20:
1387 if len(node) < 20 or len(fnode) < 20:
1385 op.ui.debug('received incomplete .hgtags fnodes data, ignoring\n')
1388 op.ui.debug('received incomplete .hgtags fnodes data, ignoring\n')
1386 break
1389 break
1387 cache.setfnode(node, fnode)
1390 cache.setfnode(node, fnode)
1388 count += 1
1391 count += 1
1389
1392
1390 cache.write()
1393 cache.write()
1391 op.ui.debug('applied %i hgtags fnodes cache entries\n' % count)
1394 op.ui.debug('applied %i hgtags fnodes cache entries\n' % count)
General Comments 0
You need to be logged in to leave comments. Login now