/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/smart/protocol.py

Merge from bzr.dev.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2010 Canonical Ltd
 
1
# Copyright (C) 2006, 2007 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
"""Wire-level encoding and decoding of requests and responses for the smart
18
18
client and server.
21
21
import collections
22
22
from cStringIO import StringIO
23
23
import struct
24
 
import sys
25
 
import thread
26
 
import threading
27
24
import time
28
25
 
29
26
import bzrlib
30
 
from bzrlib import (
31
 
    debug,
32
 
    errors,
33
 
    osutils,
34
 
    )
 
27
from bzrlib import debug
 
28
from bzrlib import errors
35
29
from bzrlib.smart import message, request
36
30
from bzrlib.trace import log_exception_quietly, mutter
37
 
from bzrlib.bencode import bdecode_as_tuple, bencode
 
31
from bzrlib.util.bencode import bdecode, bencode
38
32
 
39
33
 
40
34
# Protocol version strings.  These are sent as prefixes of bzr requests and
43
37
REQUEST_VERSION_TWO = 'bzr request 2\n'
44
38
RESPONSE_VERSION_TWO = 'bzr response 2\n'
45
39
 
46
 
MESSAGE_VERSION_THREE = 'bzr message 3 (bzr 1.6)\n'
 
40
MESSAGE_VERSION_THREE = 'bzr message 3 (bzr 1.3)\n'
47
41
RESPONSE_VERSION_THREE = REQUEST_VERSION_THREE = MESSAGE_VERSION_THREE
48
42
 
49
43
 
62
56
 
63
57
def _encode_tuple(args):
64
58
    """Encode the tuple args to a bytestream."""
65
 
    joined = '\x01'.join(args) + '\n'
66
 
    if type(joined) is unicode:
67
 
        # XXX: We should fix things so this never happens!  -AJB, 20100304
68
 
        mutter('response args contain unicode, should be only bytes: %r',
69
 
               joined)
70
 
        joined = joined.encode('ascii')
71
 
    return joined
 
59
    return '\x01'.join(args) + '\n'
72
60
 
73
61
 
74
62
class Requester(object):
101
89
        """
102
90
        raise NotImplementedError(self.call_with_body_readv_array)
103
91
 
104
 
    def set_headers(self, headers):
105
 
        raise NotImplementedError(self.set_headers)
106
 
 
107
92
 
108
93
class SmartProtocolBase(object):
109
94
    """Methods common to client and server"""
120
105
        for start, length in offsets:
121
106
            txt.append('%d,%d' % (start, length))
122
107
        return '\n'.join(txt)
123
 
 
 
108
        
124
109
 
125
110
class SmartServerRequestProtocolOne(SmartProtocolBase):
126
111
    """Server-side encoding and decoding logic for smart version 1."""
127
 
 
128
 
    def __init__(self, backing_transport, write_func, root_client_path='/',
129
 
            jail_root=None):
 
112
    
 
113
    def __init__(self, backing_transport, write_func, root_client_path='/'):
130
114
        self._backing_transport = backing_transport
131
115
        self._root_client_path = root_client_path
132
 
        self._jail_root = jail_root
133
116
        self.unused_data = ''
134
117
        self._finished = False
135
118
        self.in_buffer = ''
136
 
        self._has_dispatched = False
 
119
        self.has_dispatched = False
137
120
        self.request = None
138
121
        self._body_decoder = None
139
122
        self._write_func = write_func
140
123
 
141
124
    def accept_bytes(self, bytes):
142
125
        """Take bytes, and advance the internal state machine appropriately.
143
 
 
 
126
        
144
127
        :param bytes: must be a byte string
145
128
        """
146
129
        if not isinstance(bytes, str):
147
130
            raise ValueError(bytes)
148
131
        self.in_buffer += bytes
149
 
        if not self._has_dispatched:
 
132
        if not self.has_dispatched:
150
133
            if '\n' not in self.in_buffer:
151
134
                # no command line yet
152
135
                return
153
 
            self._has_dispatched = True
 
136
            self.has_dispatched = True
154
137
            try:
155
138
                first_line, self.in_buffer = self.in_buffer.split('\n', 1)
156
139
                first_line += '\n'
157
140
                req_args = _decode_tuple(first_line)
158
141
                self.request = request.SmartServerRequestHandler(
159
142
                    self._backing_transport, commands=request.request_handlers,
160
 
                    root_client_path=self._root_client_path,
161
 
                    jail_root=self._jail_root)
162
 
                self.request.args_received(req_args)
 
143
                    root_client_path=self._root_client_path)
 
144
                self.request.dispatch_command(req_args[0], req_args[1:])
163
145
                if self.request.finished_reading:
164
146
                    # trivial request
165
147
                    self.unused_data = self.in_buffer
181
163
                    ('error', str(exception))))
182
164
                return
183
165
 
184
 
        if self._has_dispatched:
 
166
        if self.has_dispatched:
185
167
            if self._finished:
186
 
                # nothing to do.XXX: this routine should be a single state
 
168
                # nothing to do.XXX: this routine should be a single state 
187
169
                # machine too.
188
170
                self.unused_data += self.in_buffer
189
171
                self.in_buffer = ''
225
207
 
226
208
    def _write_protocol_version(self):
227
209
        """Write any prefixes this protocol requires.
228
 
 
 
210
        
229
211
        Version one doesn't send protocol versions.
230
212
        """
231
213
 
248
230
 
249
231
class SmartServerRequestProtocolTwo(SmartServerRequestProtocolOne):
250
232
    r"""Version two of the server side of the smart protocol.
251
 
 
 
233
   
252
234
    This prefixes responses with the value of RESPONSE_VERSION_TWO.
253
235
    """
254
236
 
264
246
 
265
247
    def _write_protocol_version(self):
266
248
        r"""Write any prefixes this protocol requires.
267
 
 
 
249
        
268
250
        Version two sends the value of RESPONSE_VERSION_TWO.
269
251
        """
270
252
        self._write_func(self.response_marker)
316
298
    """
317
299
 
318
300
    def __init__(self, count=None):
319
 
        """Constructor.
320
 
 
321
 
        :param count: the total number of bytes needed by the current state.
322
 
            May be None if the number of bytes needed is unknown.
323
 
        """
324
301
        self.count = count
325
302
 
326
303
 
327
304
class _StatefulDecoder(object):
328
 
    """Base class for writing state machines to decode byte streams.
329
 
 
330
 
    Subclasses should provide a self.state_accept attribute that accepts bytes
331
 
    and, if appropriate, updates self.state_accept to a different function.
332
 
    accept_bytes will call state_accept as often as necessary to make sure the
333
 
    state machine has progressed as far as possible before it returns.
334
 
 
335
 
    See ProtocolThreeDecoder for an example subclass.
336
 
    """
337
305
 
338
306
    def __init__(self):
339
307
        self.finished_reading = False
340
 
        self._in_buffer_list = []
341
 
        self._in_buffer_len = 0
342
308
        self.unused_data = ''
343
309
        self.bytes_left = None
344
310
        self._number_needed_bytes = None
345
311
 
346
 
    def _get_in_buffer(self):
347
 
        if len(self._in_buffer_list) == 1:
348
 
            return self._in_buffer_list[0]
349
 
        in_buffer = ''.join(self._in_buffer_list)
350
 
        if len(in_buffer) != self._in_buffer_len:
351
 
            raise AssertionError(
352
 
                "Length of buffer did not match expected value: %s != %s"
353
 
                % self._in_buffer_len, len(in_buffer))
354
 
        self._in_buffer_list = [in_buffer]
355
 
        return in_buffer
356
 
 
357
 
    def _get_in_bytes(self, count):
358
 
        """Grab X bytes from the input_buffer.
359
 
 
360
 
        Callers should have already checked that self._in_buffer_len is >
361
 
        count. Note, this does not consume the bytes from the buffer. The
362
 
        caller will still need to call _get_in_buffer() and then
363
 
        _set_in_buffer() if they actually need to consume the bytes.
364
 
        """
365
 
        # check if we can yield the bytes from just the first entry in our list
366
 
        if len(self._in_buffer_list) == 0:
367
 
            raise AssertionError('Callers must be sure we have buffered bytes'
368
 
                ' before calling _get_in_bytes')
369
 
        if len(self._in_buffer_list[0]) > count:
370
 
            return self._in_buffer_list[0][:count]
371
 
        # We can't yield it from the first buffer, so collapse all buffers, and
372
 
        # yield it from that
373
 
        in_buf = self._get_in_buffer()
374
 
        return in_buf[:count]
375
 
 
376
 
    def _set_in_buffer(self, new_buf):
377
 
        if new_buf is not None:
378
 
            self._in_buffer_list = [new_buf]
379
 
            self._in_buffer_len = len(new_buf)
380
 
        else:
381
 
            self._in_buffer_list = []
382
 
            self._in_buffer_len = 0
383
 
 
384
312
    def accept_bytes(self, bytes):
385
313
        """Decode as much of bytes as possible.
386
314
 
391
319
        data will be appended to self.unused_data.
392
320
        """
393
321
        # accept_bytes is allowed to change the state
 
322
        current_state = self.state_accept
394
323
        self._number_needed_bytes = None
395
 
        # lsprof puts a very large amount of time on this specific call for
396
 
        # large readv arrays
397
 
        self._in_buffer_list.append(bytes)
398
 
        self._in_buffer_len += len(bytes)
399
324
        try:
400
 
            # Run the function for the current state.
401
 
            current_state = self.state_accept
402
 
            self.state_accept()
 
325
            self.state_accept(bytes)
403
326
            while current_state != self.state_accept:
404
 
                # The current state has changed.  Run the function for the new
405
 
                # current state, so that it can:
406
 
                #   - decode any unconsumed bytes left in a buffer, and
407
 
                #   - signal how many more bytes are expected (via raising
408
 
                #     _NeedMoreBytes).
409
327
                current_state = self.state_accept
410
 
                self.state_accept()
 
328
                self.state_accept('')
411
329
        except _NeedMoreBytes, e:
412
330
            self._number_needed_bytes = e.count
413
331
 
422
340
    def __init__(self):
423
341
        _StatefulDecoder.__init__(self)
424
342
        self.state_accept = self._state_accept_expecting_header
 
343
        self._in_buffer = ''
425
344
        self.chunk_in_progress = None
426
345
        self.chunks = collections.deque()
427
346
        self.error = False
428
347
        self.error_in_progress = None
429
 
 
 
348
    
430
349
    def next_read_size(self):
431
350
        # Note: the shortest possible chunk is 2 bytes: '0\n', and the
432
351
        # end-of-body marker is 4 bytes: 'END\n'.
435
354
            # the rest of this chunk plus an END chunk.
436
355
            return self.bytes_left + 4
437
356
        elif self.state_accept == self._state_accept_expecting_length:
438
 
            if self._in_buffer_len == 0:
 
357
            if self._in_buffer == '':
439
358
                # We're expecting a chunk length.  There's at least two bytes
440
359
                # left: a digit plus '\n'.
441
360
                return 2
446
365
        elif self.state_accept == self._state_accept_reading_unused:
447
366
            return 1
448
367
        elif self.state_accept == self._state_accept_expecting_header:
449
 
            return max(0, len('chunked\n') - self._in_buffer_len)
 
368
            return max(0, len('chunked\n') - len(self._in_buffer))
450
369
        else:
451
370
            raise AssertionError("Impossible state: %r" % (self.state_accept,))
452
371
 
457
376
            return None
458
377
 
459
378
    def _extract_line(self):
460
 
        in_buf = self._get_in_buffer()
461
 
        pos = in_buf.find('\n')
 
379
        pos = self._in_buffer.find('\n')
462
380
        if pos == -1:
463
 
            # We haven't read a complete line yet, so request more bytes before
464
 
            # we continue.
 
381
            # We haven't read a complete line yet, so there's nothing to do.
465
382
            raise _NeedMoreBytes(1)
466
 
        line = in_buf[:pos]
 
383
        line = self._in_buffer[:pos]
467
384
        # Trim the prefix (including '\n' delimiter) from the _in_buffer.
468
 
        self._set_in_buffer(in_buf[pos+1:])
 
385
        self._in_buffer = self._in_buffer[pos+1:]
469
386
        return line
470
387
 
471
388
    def _finished(self):
472
 
        self.unused_data = self._get_in_buffer()
473
 
        self._in_buffer_list = []
474
 
        self._in_buffer_len = 0
 
389
        self.unused_data = self._in_buffer
 
390
        self._in_buffer = None
475
391
        self.state_accept = self._state_accept_reading_unused
476
392
        if self.error:
477
393
            error_args = tuple(self.error_in_progress)
479
395
            self.error_in_progress = None
480
396
        self.finished_reading = True
481
397
 
482
 
    def _state_accept_expecting_header(self):
 
398
    def _state_accept_expecting_header(self, bytes):
 
399
        self._in_buffer += bytes
483
400
        prefix = self._extract_line()
484
401
        if prefix == 'chunked':
485
402
            self.state_accept = self._state_accept_expecting_length
487
404
            raise errors.SmartProtocolError(
488
405
                'Bad chunked body header: "%s"' % (prefix,))
489
406
 
490
 
    def _state_accept_expecting_length(self):
 
407
    def _state_accept_expecting_length(self, bytes):
 
408
        self._in_buffer += bytes
491
409
        prefix = self._extract_line()
492
410
        if prefix == 'ERR':
493
411
            self.error = True
494
412
            self.error_in_progress = []
495
 
            self._state_accept_expecting_length()
 
413
            self._state_accept_expecting_length('')
496
414
            return
497
415
        elif prefix == 'END':
498
416
            # We've read the end-of-body marker.
505
423
            self.chunk_in_progress = ''
506
424
            self.state_accept = self._state_accept_reading_chunk
507
425
 
508
 
    def _state_accept_reading_chunk(self):
509
 
        in_buf = self._get_in_buffer()
510
 
        in_buffer_len = len(in_buf)
511
 
        self.chunk_in_progress += in_buf[:self.bytes_left]
512
 
        self._set_in_buffer(in_buf[self.bytes_left:])
 
426
    def _state_accept_reading_chunk(self, bytes):
 
427
        self._in_buffer += bytes
 
428
        in_buffer_len = len(self._in_buffer)
 
429
        self.chunk_in_progress += self._in_buffer[:self.bytes_left]
 
430
        self._in_buffer = self._in_buffer[self.bytes_left:]
513
431
        self.bytes_left -= in_buffer_len
514
432
        if self.bytes_left <= 0:
515
433
            # Finished with chunk
520
438
                self.chunks.append(self.chunk_in_progress)
521
439
            self.chunk_in_progress = None
522
440
            self.state_accept = self._state_accept_expecting_length
523
 
 
524
 
    def _state_accept_reading_unused(self):
525
 
        self.unused_data += self._get_in_buffer()
526
 
        self._in_buffer_list = []
 
441
        
 
442
    def _state_accept_reading_unused(self, bytes):
 
443
        self.unused_data += bytes
527
444
 
528
445
 
529
446
class LengthPrefixedBodyDecoder(_StatefulDecoder):
530
447
    """Decodes the length-prefixed bulk data."""
531
 
 
 
448
    
532
449
    def __init__(self):
533
450
        _StatefulDecoder.__init__(self)
534
451
        self.state_accept = self._state_accept_expecting_length
535
452
        self.state_read = self._state_read_no_data
536
 
        self._body = ''
 
453
        self._in_buffer = ''
537
454
        self._trailer_buffer = ''
538
 
 
 
455
    
539
456
    def next_read_size(self):
540
457
        if self.bytes_left is not None:
541
458
            # Ideally we want to read all the remainder of the body and the
551
468
        else:
552
469
            # Reading excess data.  Either way, 1 byte at a time is fine.
553
470
            return 1
554
 
 
 
471
        
555
472
    def read_pending_data(self):
556
473
        """Return any pending data that has been decoded."""
557
474
        return self.state_read()
558
475
 
559
 
    def _state_accept_expecting_length(self):
560
 
        in_buf = self._get_in_buffer()
561
 
        pos = in_buf.find('\n')
 
476
    def _state_accept_expecting_length(self, bytes):
 
477
        self._in_buffer += bytes
 
478
        pos = self._in_buffer.find('\n')
562
479
        if pos == -1:
563
480
            return
564
 
        self.bytes_left = int(in_buf[:pos])
565
 
        self._set_in_buffer(in_buf[pos+1:])
 
481
        self.bytes_left = int(self._in_buffer[:pos])
 
482
        self._in_buffer = self._in_buffer[pos+1:]
 
483
        self.bytes_left -= len(self._in_buffer)
566
484
        self.state_accept = self._state_accept_reading_body
567
 
        self.state_read = self._state_read_body_buffer
 
485
        self.state_read = self._state_read_in_buffer
568
486
 
569
 
    def _state_accept_reading_body(self):
570
 
        in_buf = self._get_in_buffer()
571
 
        self._body += in_buf
572
 
        self.bytes_left -= len(in_buf)
573
 
        self._set_in_buffer(None)
 
487
    def _state_accept_reading_body(self, bytes):
 
488
        self._in_buffer += bytes
 
489
        self.bytes_left -= len(bytes)
574
490
        if self.bytes_left <= 0:
575
491
            # Finished with body
576
492
            if self.bytes_left != 0:
577
 
                self._trailer_buffer = self._body[self.bytes_left:]
578
 
                self._body = self._body[:self.bytes_left]
 
493
                self._trailer_buffer = self._in_buffer[self.bytes_left:]
 
494
                self._in_buffer = self._in_buffer[:self.bytes_left]
579
495
            self.bytes_left = None
580
496
            self.state_accept = self._state_accept_reading_trailer
581
 
 
582
 
    def _state_accept_reading_trailer(self):
583
 
        self._trailer_buffer += self._get_in_buffer()
584
 
        self._set_in_buffer(None)
 
497
        
 
498
    def _state_accept_reading_trailer(self, bytes):
 
499
        self._trailer_buffer += bytes
585
500
        # TODO: what if the trailer does not match "done\n"?  Should this raise
586
501
        # a ProtocolViolation exception?
587
502
        if self._trailer_buffer.startswith('done\n'):
588
503
            self.unused_data = self._trailer_buffer[len('done\n'):]
589
504
            self.state_accept = self._state_accept_reading_unused
590
505
            self.finished_reading = True
591
 
 
592
 
    def _state_accept_reading_unused(self):
593
 
        self.unused_data += self._get_in_buffer()
594
 
        self._set_in_buffer(None)
 
506
    
 
507
    def _state_accept_reading_unused(self, bytes):
 
508
        self.unused_data += bytes
595
509
 
596
510
    def _state_read_no_data(self):
597
511
        return ''
598
512
 
599
 
    def _state_read_body_buffer(self):
600
 
        result = self._body
601
 
        self._body = ''
 
513
    def _state_read_in_buffer(self):
 
514
        result = self._in_buffer
 
515
        self._in_buffer = ''
602
516
        return result
603
517
 
604
518
 
605
519
class SmartClientRequestProtocolOne(SmartProtocolBase, Requester,
606
 
                                    message.ResponseHandler):
 
520
        message.ResponseHandler):
607
521
    """The client-side protocol for smart version 1."""
608
522
 
609
523
    def __init__(self, request):
616
530
        self._body_buffer = None
617
531
        self._request_start_time = None
618
532
        self._last_verb = None
619
 
        self._headers = None
620
 
 
621
 
    def set_headers(self, headers):
622
 
        self._headers = dict(headers)
623
533
 
624
534
    def call(self, *args):
625
535
        if 'hpss' in debug.debug_flags:
626
536
            mutter('hpss call:   %s', repr(args)[1:-1])
627
537
            if getattr(self._request._medium, 'base', None) is not None:
628
538
                mutter('             (to %s)', self._request._medium.base)
629
 
            self._request_start_time = osutils.timer_func()
 
539
            self._request_start_time = time.time()
630
540
        self._write_args(args)
631
541
        self._request.finished_writing()
632
542
        self._last_verb = args[0]
641
551
            if getattr(self._request._medium, '_path', None) is not None:
642
552
                mutter('                  (to %s)', self._request._medium._path)
643
553
            mutter('              %d bytes', len(body))
644
 
            self._request_start_time = osutils.timer_func()
 
554
            self._request_start_time = time.time()
645
555
            if 'hpssdetail' in debug.debug_flags:
646
556
                mutter('hpss body content: %s', body)
647
557
        self._write_args(args)
660
570
            mutter('hpss call w/readv: %s', repr(args)[1:-1])
661
571
            if getattr(self._request._medium, '_path', None) is not None:
662
572
                mutter('                  (to %s)', self._request._medium._path)
663
 
            self._request_start_time = osutils.timer_func()
 
573
            self._request_start_time = time.time()
664
574
        self._write_args(args)
665
575
        readv_bytes = self._serialise_offsets(body)
666
576
        bytes = self._encode_bulk_data(readv_bytes)
670
580
            mutter('              %d bytes in readv request', len(readv_bytes))
671
581
        self._last_verb = args[0]
672
582
 
673
 
    def call_with_body_stream(self, args, stream):
674
 
        # Protocols v1 and v2 don't support body streams.  So it's safe to
675
 
        # assume that a v1/v2 server doesn't support whatever method we're
676
 
        # trying to call with a body stream.
677
 
        self._request.finished_writing()
678
 
        self._request.finished_reading()
679
 
        raise errors.UnknownSmartMethod(args[0])
680
 
 
681
583
    def cancel_read_body(self):
682
584
        """After expecting a body, a response code may indicate one otherwise.
683
585
 
692
594
        if 'hpss' in debug.debug_flags:
693
595
            if self._request_start_time is not None:
694
596
                mutter('   result:   %6.3fs  %s',
695
 
                       osutils.timer_func() - self._request_start_time,
 
597
                       time.time() - self._request_start_time,
696
598
                       repr(result)[1:-1])
697
599
                self._request_start_time = None
698
600
            else:
712
614
        return result
713
615
 
714
616
    def _raise_args_if_error(self, result_tuple):
715
 
        # Later protocol versions have an explicit flag in the protocol to say
716
 
        # if an error response is "failed" or not.  In version 1 we don't have
717
 
        # that luxury.  So here is a complete list of errors that can be
718
 
        # returned in response to existing version 1 smart requests.  Responses
719
 
        # starting with these codes are always "failed" responses.
720
617
        v1_error_codes = [
721
618
            'norepository',
722
619
            'NoSuchFile',
743
640
    def _response_is_unknown_method(self, result_tuple):
744
641
        """Raise UnexpectedSmartServerResponse if the response is an 'unknonwn
745
642
        method' response to the request.
746
 
 
 
643
        
747
644
        :param response: The response from a smart client call_expecting_body
748
645
            call.
749
646
        :param verb: The verb used in that call.
756
653
            # The response will have no body, so we've finished reading.
757
654
            self._request.finished_reading()
758
655
            raise errors.UnknownSmartMethod(self._last_verb)
759
 
 
 
656
        
760
657
    def read_body_bytes(self, count=-1):
761
658
        """Read bytes from the body, decoding into a byte stream.
762
 
 
763
 
        We read all bytes at once to ensure we've checked the trailer for
 
659
        
 
660
        We read all bytes at once to ensure we've checked the trailer for 
764
661
        errors, and then feed the buffer back as read_body_bytes is called.
765
662
        """
766
663
        if self._body_buffer is not None:
767
664
            return self._body_buffer.read(count)
768
665
        _body_decoder = LengthPrefixedBodyDecoder()
769
666
 
 
667
        # Read no more than 64k at a time so that we don't risk error 10055 (no
 
668
        # buffer space available) on Windows.
 
669
        max_read = 64 * 1024
770
670
        while not _body_decoder.finished_reading:
771
 
            bytes = self._request.read_bytes(_body_decoder.next_read_size())
772
 
            if bytes == '':
773
 
                # end of file encountered reading from server
774
 
                raise errors.ConnectionReset(
775
 
                    "Connection lost while reading response body.")
 
671
            bytes_wanted = min(_body_decoder.next_read_size(), max_read)
 
672
            bytes = self._request.read_bytes(bytes_wanted)
776
673
            _body_decoder.accept_bytes(bytes)
777
674
        self._request.finished_reading()
778
675
        self._body_buffer = StringIO(_body_decoder.read_pending_data())
784
681
 
785
682
    def _recv_tuple(self):
786
683
        """Receive a tuple from the medium request."""
787
 
        return _decode_tuple(self._request.read_line())
 
684
        return _decode_tuple(self._recv_line())
 
685
 
 
686
    def _recv_line(self):
 
687
        """Read an entire line from the medium request."""
 
688
        line = ''
 
689
        while not line or line[-1] != '\n':
 
690
            # TODO: this is inefficient - but tuples are short.
 
691
            new_char = self._request.read_bytes(1)
 
692
            if new_char == '':
 
693
                # end of file encountered reading from server
 
694
                raise errors.ConnectionReset(
 
695
                    "please check connectivity and permissions",
 
696
                    "(and try -Dhpss if further diagnosis is required)")
 
697
            line += new_char
 
698
        return line
788
699
 
789
700
    def query_version(self):
790
701
        """Return protocol version number of the server."""
794
705
            return 1
795
706
        elif resp == ('ok', '2'):
796
707
            return 2
 
708
        elif resp == ('ok', '3'):
 
709
            return 3
797
710
        else:
798
711
            raise errors.SmartProtocolError("bad response %r" % (resp,))
799
712
 
804
717
 
805
718
    def _write_protocol_version(self):
806
719
        """Write any prefixes this protocol requires.
807
 
 
 
720
        
808
721
        Version one doesn't send protocol versions.
809
722
        """
810
723
 
811
724
 
812
725
class SmartClientRequestProtocolTwo(SmartClientRequestProtocolOne):
813
726
    """Version two of the client side of the smart protocol.
814
 
 
 
727
    
815
728
    This prefixes the request with the value of REQUEST_VERSION_TWO.
816
729
    """
817
730
 
825
738
        """
826
739
        version = self._request.read_line()
827
740
        if version != self.response_marker:
828
 
            self._request.finished_reading()
829
 
            raise errors.UnexpectedProtocolVersionMarker(version)
830
 
        response_status = self._request.read_line()
 
741
            raise errors.SmartProtocolError('bad protocol marker %r' % version)
 
742
        response_status = self._recv_line()
831
743
        result = SmartClientRequestProtocolOne._read_response_tuple(self)
832
 
        self._response_is_unknown_method(result)
833
744
        if response_status == 'success\n':
834
745
            self.response_status = True
835
746
            if not expect_body:
845
756
 
846
757
    def _write_protocol_version(self):
847
758
        """Write any prefixes this protocol requires.
848
 
 
 
759
        
849
760
        Version two sends the value of REQUEST_VERSION_TWO.
850
761
        """
851
762
        self._request.accept_bytes(self.request_marker)
855
766
        """
856
767
        # Read no more than 64k at a time so that we don't risk error 10055 (no
857
768
        # buffer space available) on Windows.
 
769
        max_read = 64 * 1024
858
770
        _body_decoder = ChunkedBodyDecoder()
859
771
        while not _body_decoder.finished_reading:
860
 
            bytes = self._request.read_bytes(_body_decoder.next_read_size())
861
 
            if bytes == '':
862
 
                # end of file encountered reading from server
863
 
                raise errors.ConnectionReset(
864
 
                    "Connection lost while reading streamed body.")
 
772
            bytes_wanted = min(_body_decoder.next_read_size(), max_read)
 
773
            bytes = self._request.read_bytes(bytes_wanted)
865
774
            _body_decoder.accept_bytes(bytes)
866
775
            for body_bytes in iter(_body_decoder.read_next_chunk, None):
867
776
                if 'hpss' in debug.debug_flags and type(body_bytes) is str:
872
781
 
873
782
 
874
783
def build_server_protocol_three(backing_transport, write_func,
875
 
                                root_client_path, jail_root=None):
 
784
                                root_client_path):
876
785
    request_handler = request.SmartServerRequestHandler(
877
786
        backing_transport, commands=request.request_handlers,
878
 
        root_client_path=root_client_path, jail_root=jail_root)
 
787
        root_client_path=root_client_path)
879
788
    responder = ProtocolThreeResponder(write_func)
880
789
    message_handler = message.ConventionalRequestHandler(request_handler, responder)
881
790
    return ProtocolThreeDecoder(message_handler)
886
795
    response_marker = RESPONSE_VERSION_THREE
887
796
    request_marker = REQUEST_VERSION_THREE
888
797
 
889
 
    def __init__(self, message_handler, expect_version_marker=False):
 
798
    def __init__(self, message_handler):
890
799
        _StatefulDecoder.__init__(self)
891
 
        self._has_dispatched = False
 
800
        self.has_dispatched = False
892
801
        # Initial state
893
 
        if expect_version_marker:
894
 
            self.state_accept = self._state_accept_expecting_protocol_version
895
 
            # We're expecting at least the protocol version marker + some
896
 
            # headers.
897
 
            self._number_needed_bytes = len(MESSAGE_VERSION_THREE) + 4
898
 
        else:
899
 
            self.state_accept = self._state_accept_expecting_headers
900
 
            self._number_needed_bytes = 4
901
 
        self.decoding_failed = False
 
802
        self._in_buffer = ''
 
803
        self._number_needed_bytes = 4
 
804
        self.state_accept = self._state_accept_expecting_headers
 
805
        self.errored = False
 
806
 
902
807
        self.request_handler = self.message_handler = message_handler
903
808
 
904
809
    def accept_bytes(self, bytes):
907
812
            _StatefulDecoder.accept_bytes(self, bytes)
908
813
        except KeyboardInterrupt:
909
814
            raise
910
 
        except errors.SmartMessageHandlerError, exception:
911
 
            # We do *not* set self.decoding_failed here.  The message handler
912
 
            # has raised an error, but the decoder is still able to parse bytes
913
 
            # and determine when this message ends.
914
 
            if not isinstance(exception.exc_value, errors.UnknownSmartMethod):
915
 
                log_exception_quietly()
916
 
            self.message_handler.protocol_error(exception.exc_value)
917
 
            # The state machine is ready to continue decoding, but the
918
 
            # exception has interrupted the loop that runs the state machine.
919
 
            # So we call accept_bytes again to restart it.
920
 
            self.accept_bytes('')
921
815
        except Exception, exception:
922
 
            # The decoder itself has raised an exception.  We cannot continue
923
 
            # decoding.
924
 
            self.decoding_failed = True
925
 
            if isinstance(exception, errors.UnexpectedProtocolVersionMarker):
926
 
                # This happens during normal operation when the client tries a
927
 
                # protocol version the server doesn't understand, so no need to
928
 
                # log a traceback every time.
929
 
                # Note that this can only happen when
930
 
                # expect_version_marker=True, which is only the case on the
931
 
                # client side.
932
 
                pass
933
 
            else:
934
 
                log_exception_quietly()
 
816
            log_exception_quietly()
935
817
            self.message_handler.protocol_error(exception)
 
818
            self.errored = True
936
819
 
937
820
    def _extract_length_prefixed_bytes(self):
938
 
        if self._in_buffer_len < 4:
 
821
        if len(self._in_buffer) < 4:
939
822
            # A length prefix by itself is 4 bytes, and we don't even have that
940
823
            # many yet.
941
824
            raise _NeedMoreBytes(4)
942
 
        (length,) = struct.unpack('!L', self._get_in_bytes(4))
 
825
        (length,) = struct.unpack('!L', self._in_buffer[:4])
943
826
        end_of_bytes = 4 + length
944
 
        if self._in_buffer_len < end_of_bytes:
 
827
        if len(self._in_buffer) < end_of_bytes:
945
828
            # We haven't yet read as many bytes as the length-prefix says there
946
829
            # are.
947
830
            raise _NeedMoreBytes(end_of_bytes)
948
831
        # Extract the bytes from the buffer.
949
 
        in_buf = self._get_in_buffer()
950
 
        bytes = in_buf[4:end_of_bytes]
951
 
        self._set_in_buffer(in_buf[end_of_bytes:])
 
832
        bytes = self._in_buffer[4:end_of_bytes]
 
833
        self._in_buffer = self._in_buffer[end_of_bytes:]
952
834
        return bytes
953
835
 
954
836
    def _extract_prefixed_bencoded_data(self):
955
837
        prefixed_bytes = self._extract_length_prefixed_bytes()
956
838
        try:
957
 
            decoded = bdecode_as_tuple(prefixed_bytes)
 
839
            decoded = bdecode(prefixed_bytes)
958
840
        except ValueError:
959
841
            raise errors.SmartProtocolError(
960
842
                'Bytes %r not bencoded' % (prefixed_bytes,))
961
843
        return decoded
962
844
 
963
845
    def _extract_single_byte(self):
964
 
        if self._in_buffer_len == 0:
 
846
        if self._in_buffer == '':
965
847
            # The buffer is empty
966
848
            raise _NeedMoreBytes(1)
967
 
        in_buf = self._get_in_buffer()
968
 
        one_byte = in_buf[0]
969
 
        self._set_in_buffer(in_buf[1:])
 
849
        one_byte = self._in_buffer[0]
 
850
        self._in_buffer = self._in_buffer[1:]
970
851
        return one_byte
971
852
 
972
 
    def _state_accept_expecting_protocol_version(self):
973
 
        needed_bytes = len(MESSAGE_VERSION_THREE) - self._in_buffer_len
974
 
        in_buf = self._get_in_buffer()
975
 
        if needed_bytes > 0:
976
 
            # We don't have enough bytes to check if the protocol version
977
 
            # marker is right.  But we can check if it is already wrong by
978
 
            # checking that the start of MESSAGE_VERSION_THREE matches what
979
 
            # we've read so far.
980
 
            # [In fact, if the remote end isn't bzr we might never receive
981
 
            # len(MESSAGE_VERSION_THREE) bytes.  So if the bytes we have so far
982
 
            # are wrong then we should just raise immediately rather than
983
 
            # stall.]
984
 
            if not MESSAGE_VERSION_THREE.startswith(in_buf):
985
 
                # We have enough bytes to know the protocol version is wrong
986
 
                raise errors.UnexpectedProtocolVersionMarker(in_buf)
987
 
            raise _NeedMoreBytes(len(MESSAGE_VERSION_THREE))
988
 
        if not in_buf.startswith(MESSAGE_VERSION_THREE):
989
 
            raise errors.UnexpectedProtocolVersionMarker(in_buf)
990
 
        self._set_in_buffer(in_buf[len(MESSAGE_VERSION_THREE):])
991
 
        self.state_accept = self._state_accept_expecting_headers
992
 
 
993
 
    def _state_accept_expecting_headers(self):
 
853
    def _state_accept_expecting_headers(self, bytes):
 
854
        self._in_buffer += bytes
994
855
        decoded = self._extract_prefixed_bencoded_data()
995
856
        if type(decoded) is not dict:
996
857
            raise errors.SmartProtocolError(
997
858
                'Header object %r is not a dict' % (decoded,))
 
859
        self.message_handler.headers_received(decoded)
998
860
        self.state_accept = self._state_accept_expecting_message_part
999
 
        try:
1000
 
            self.message_handler.headers_received(decoded)
1001
 
        except:
1002
 
            raise errors.SmartMessageHandlerError(sys.exc_info())
1003
 
 
1004
 
    def _state_accept_expecting_message_part(self):
 
861
    
 
862
    def _state_accept_expecting_message_part(self, bytes):
 
863
        self._in_buffer += bytes
1005
864
        message_part_kind = self._extract_single_byte()
1006
865
        if message_part_kind == 'o':
1007
866
            self.state_accept = self._state_accept_expecting_one_byte
1015
874
            raise errors.SmartProtocolError(
1016
875
                'Bad message kind byte: %r' % (message_part_kind,))
1017
876
 
1018
 
    def _state_accept_expecting_one_byte(self):
 
877
    def _state_accept_expecting_one_byte(self, bytes):
 
878
        self._in_buffer += bytes
1019
879
        byte = self._extract_single_byte()
 
880
        self.message_handler.byte_part_received(byte)
1020
881
        self.state_accept = self._state_accept_expecting_message_part
1021
 
        try:
1022
 
            self.message_handler.byte_part_received(byte)
1023
 
        except:
1024
 
            raise errors.SmartMessageHandlerError(sys.exc_info())
1025
882
 
1026
 
    def _state_accept_expecting_bytes(self):
 
883
    def _state_accept_expecting_bytes(self, bytes):
1027
884
        # XXX: this should not buffer whole message part, but instead deliver
1028
885
        # the bytes as they arrive.
 
886
        self._in_buffer += bytes
1029
887
        prefixed_bytes = self._extract_length_prefixed_bytes()
 
888
        self.message_handler.bytes_part_received(prefixed_bytes)
1030
889
        self.state_accept = self._state_accept_expecting_message_part
1031
 
        try:
1032
 
            self.message_handler.bytes_part_received(prefixed_bytes)
1033
 
        except:
1034
 
            raise errors.SmartMessageHandlerError(sys.exc_info())
1035
890
 
1036
 
    def _state_accept_expecting_structure(self):
 
891
    def _state_accept_expecting_structure(self, bytes):
 
892
        self._in_buffer += bytes
1037
893
        structure = self._extract_prefixed_bencoded_data()
 
894
        self.message_handler.structure_part_received(structure)
1038
895
        self.state_accept = self._state_accept_expecting_message_part
1039
 
        try:
1040
 
            self.message_handler.structure_part_received(structure)
1041
 
        except:
1042
 
            raise errors.SmartMessageHandlerError(sys.exc_info())
1043
896
 
1044
897
    def done(self):
1045
 
        self.unused_data = self._get_in_buffer()
1046
 
        self._set_in_buffer(None)
 
898
        self.unused_data = self._in_buffer
 
899
        self._in_buffer = None
1047
900
        self.state_accept = self._state_accept_reading_unused
1048
 
        try:
1049
 
            self.message_handler.end_received()
1050
 
        except:
1051
 
            raise errors.SmartMessageHandlerError(sys.exc_info())
 
901
        self.message_handler.end_received()
1052
902
 
1053
 
    def _state_accept_reading_unused(self):
1054
 
        self.unused_data += self._get_in_buffer()
1055
 
        self._set_in_buffer(None)
 
903
    def _state_accept_reading_unused(self, bytes):
 
904
        self.unused_data += bytes
1056
905
 
1057
906
    def next_read_size(self):
1058
907
        if self.state_accept == self._state_accept_reading_unused:
1059
908
            return 0
1060
 
        elif self.decoding_failed:
 
909
        elif self.errored:
1061
910
            # An exception occured while processing this message, probably from
1062
911
            # self.message_handler.  We're not sure that this state machine is
1063
912
            # in a consistent state, so just signal that we're done (i.e. give
1065
914
            return 0
1066
915
        else:
1067
916
            if self._number_needed_bytes is not None:
1068
 
                return self._number_needed_bytes - self._in_buffer_len
 
917
                return self._number_needed_bytes - len(self._in_buffer)
1069
918
            else:
1070
919
                raise AssertionError("don't know how many bytes are expected!")
1071
920
 
1073
922
class _ProtocolThreeEncoder(object):
1074
923
 
1075
924
    response_marker = request_marker = MESSAGE_VERSION_THREE
1076
 
    BUFFER_SIZE = 1024*1024 # 1 MiB buffer before flushing
1077
925
 
1078
926
    def __init__(self, write_func):
1079
 
        self._buf = []
1080
 
        self._buf_len = 0
1081
 
        self._real_write_func = write_func
1082
 
 
1083
 
    def _write_func(self, bytes):
1084
 
        # TODO: It is probably more appropriate to use sum(map(len, _buf))
1085
 
        #       for total number of bytes to write, rather than buffer based on
1086
 
        #       the number of write() calls
1087
 
        # TODO: Another possibility would be to turn this into an async model.
1088
 
        #       Where we let another thread know that we have some bytes if
1089
 
        #       they want it, but we don't actually block for it
1090
 
        #       Note that osutils.send_all always sends 64kB chunks anyway, so
1091
 
        #       we might just push out smaller bits at a time?
1092
 
        self._buf.append(bytes)
1093
 
        self._buf_len += len(bytes)
1094
 
        if self._buf_len > self.BUFFER_SIZE:
1095
 
            self.flush()
1096
 
 
1097
 
    def flush(self):
1098
 
        if self._buf:
1099
 
            self._real_write_func(''.join(self._buf))
1100
 
            del self._buf[:]
1101
 
            self._buf_len = 0
 
927
        self._write_func = write_func
1102
928
 
1103
929
    def _serialise_offsets(self, offsets):
1104
930
        """Serialise a readv offset list."""
1106
932
        for start, length in offsets:
1107
933
            txt.append('%d,%d' % (start, length))
1108
934
        return '\n'.join(txt)
1109
 
 
 
935
        
1110
936
    def _write_protocol_version(self):
1111
937
        self._write_func(MESSAGE_VERSION_THREE)
1112
938
 
1115
941
        self._write_func(struct.pack('!L', len(bytes)))
1116
942
        self._write_func(bytes)
1117
943
 
1118
 
    def _write_headers(self, headers):
 
944
    def _write_headers(self, headers=None):
 
945
        if headers is None:
 
946
            headers = {'Software version': bzrlib.__version__}
1119
947
        self._write_prefixed_bencode(headers)
1120
948
 
1121
949
    def _write_structure(self, args):
1130
958
 
1131
959
    def _write_end(self):
1132
960
        self._write_func('e')
1133
 
        self.flush()
1134
961
 
1135
962
    def _write_prefixed_body(self, bytes):
1136
963
        self._write_func('b')
1137
964
        self._write_func(struct.pack('!L', len(bytes)))
1138
965
        self._write_func(bytes)
1139
966
 
1140
 
    def _write_chunked_body_start(self):
1141
 
        self._write_func('oC')
1142
 
 
1143
967
    def _write_error_status(self):
1144
968
        self._write_func('oE')
1145
969
 
1152
976
    def __init__(self, write_func):
1153
977
        _ProtocolThreeEncoder.__init__(self, write_func)
1154
978
        self.response_sent = False
1155
 
        self._headers = {'Software version': bzrlib.__version__}
1156
 
        if 'hpss' in debug.debug_flags:
1157
 
            self._thread_id = thread.get_ident()
1158
 
            self._response_start_time = None
1159
 
 
1160
 
    def _trace(self, action, message, extra_bytes=None, include_time=False):
1161
 
        if self._response_start_time is None:
1162
 
            self._response_start_time = osutils.timer_func()
1163
 
        if include_time:
1164
 
            t = '%5.3fs ' % (time.clock() - self._response_start_time)
1165
 
        else:
1166
 
            t = ''
1167
 
        if extra_bytes is None:
1168
 
            extra = ''
1169
 
        else:
1170
 
            extra = ' ' + repr(extra_bytes[:40])
1171
 
            if len(extra) > 33:
1172
 
                extra = extra[:29] + extra[-1] + '...'
1173
 
        mutter('%12s: [%s] %s%s%s'
1174
 
               % (action, self._thread_id, t, message, extra))
1175
979
 
1176
980
    def send_error(self, exception):
1177
 
        if self.response_sent:
1178
 
            raise AssertionError(
1179
 
                "send_error(%s) called, but response already sent."
1180
 
                % (exception,))
 
981
        assert not self.response_sent
1181
982
        if isinstance(exception, errors.UnknownSmartMethod):
1182
983
            failure = request.FailedSmartServerResponse(
1183
984
                ('UnknownMethod', exception.verb))
1184
985
            self.send_response(failure)
1185
986
            return
1186
 
        if 'hpss' in debug.debug_flags:
1187
 
            self._trace('error', str(exception))
1188
987
        self.response_sent = True
1189
 
        self._write_protocol_version()
1190
 
        self._write_headers(self._headers)
 
988
        self._write_headers()
1191
989
        self._write_error_status()
1192
990
        self._write_structure(('error', str(exception)))
1193
991
        self._write_end()
1194
992
 
1195
993
    def send_response(self, response):
1196
 
        if self.response_sent:
1197
 
            raise AssertionError(
1198
 
                "send_response(%r) called, but response already sent."
1199
 
                % (response,))
 
994
        assert not self.response_sent
1200
995
        self.response_sent = True
1201
 
        self._write_protocol_version()
1202
 
        self._write_headers(self._headers)
 
996
        self._write_headers()
1203
997
        if response.is_successful():
1204
998
            self._write_success_status()
1205
999
        else:
1206
1000
            self._write_error_status()
1207
 
        if 'hpss' in debug.debug_flags:
1208
 
            self._trace('response', repr(response.args))
1209
1001
        self._write_structure(response.args)
1210
1002
        if response.body is not None:
1211
1003
            self._write_prefixed_body(response.body)
1212
 
            if 'hpss' in debug.debug_flags:
1213
 
                self._trace('body', '%d bytes' % (len(response.body),),
1214
 
                            response.body, include_time=True)
1215
1004
        elif response.body_stream is not None:
1216
 
            count = num_bytes = 0
1217
 
            first_chunk = None
1218
 
            for exc_info, chunk in _iter_with_errors(response.body_stream):
1219
 
                count += 1
1220
 
                if exc_info is not None:
1221
 
                    self._write_error_status()
1222
 
                    error_struct = request._translate_error(exc_info[1])
1223
 
                    self._write_structure(error_struct)
1224
 
                    break
1225
 
                else:
1226
 
                    if isinstance(chunk, request.FailedSmartServerResponse):
1227
 
                        self._write_error_status()
1228
 
                        self._write_structure(chunk.args)
1229
 
                        break
1230
 
                    num_bytes += len(chunk)
1231
 
                    if first_chunk is None:
1232
 
                        first_chunk = chunk
1233
 
                    self._write_prefixed_body(chunk)
1234
 
                    if 'hpssdetail' in debug.debug_flags:
1235
 
                        # Not worth timing separately, as _write_func is
1236
 
                        # actually buffered
1237
 
                        self._trace('body chunk',
1238
 
                                    '%d bytes' % (len(chunk),),
1239
 
                                    chunk, suppress_time=True)
1240
 
            if 'hpss' in debug.debug_flags:
1241
 
                self._trace('body stream',
1242
 
                            '%d bytes %d chunks' % (num_bytes, count),
1243
 
                            first_chunk)
 
1005
            for chunk in response.body_stream:
 
1006
                self._write_prefixed_body(chunk)
1244
1007
        self._write_end()
1245
 
        if 'hpss' in debug.debug_flags:
1246
 
            self._trace('response end', '', include_time=True)
1247
 
 
1248
 
 
1249
 
def _iter_with_errors(iterable):
1250
 
    """Handle errors from iterable.next().
1251
 
 
1252
 
    Use like::
1253
 
 
1254
 
        for exc_info, value in _iter_with_errors(iterable):
1255
 
            ...
1256
 
 
1257
 
    This is a safer alternative to::
1258
 
 
1259
 
        try:
1260
 
            for value in iterable:
1261
 
               ...
1262
 
        except:
1263
 
            ...
1264
 
 
1265
 
    Because the latter will catch errors from the for-loop body, not just
1266
 
    iterable.next()
1267
 
 
1268
 
    If an error occurs, exc_info will be a exc_info tuple, and the generator
1269
 
    will terminate.  Otherwise exc_info will be None, and value will be the
1270
 
    value from iterable.next().  Note that KeyboardInterrupt and SystemExit
1271
 
    will not be itercepted.
1272
 
    """
1273
 
    iterator = iter(iterable)
1274
 
    while True:
1275
 
        try:
1276
 
            yield None, iterator.next()
1277
 
        except StopIteration:
1278
 
            return
1279
 
        except (KeyboardInterrupt, SystemExit):
1280
 
            raise
1281
 
        except Exception:
1282
 
            mutter('_iter_with_errors caught error')
1283
 
            log_exception_quietly()
1284
 
            yield sys.exc_info(), None
1285
 
            return
1286
 
 
 
1008
        
1287
1009
 
1288
1010
class ProtocolThreeRequester(_ProtocolThreeEncoder, Requester):
1289
1011
 
1290
1012
    def __init__(self, medium_request):
1291
1013
        _ProtocolThreeEncoder.__init__(self, medium_request.accept_bytes)
1292
1014
        self._medium_request = medium_request
1293
 
        self._headers = {}
1294
 
 
1295
 
    def set_headers(self, headers):
1296
 
        self._headers = headers.copy()
1297
 
 
1298
 
    def call(self, *args):
 
1015
 
 
1016
    def call(self, *args, **kw):
 
1017
        # XXX: ideally, signature would be call(self, *args, headers=None), but
 
1018
        # python doesn't allow that.  So, we fake it.
 
1019
        headers = None
 
1020
        if 'headers' in kw:
 
1021
            headers = kw.pop('headers')
 
1022
        if kw != {}:
 
1023
            raise TypeError('Unexpected keyword arguments: %r' % (kw,))
1299
1024
        if 'hpss' in debug.debug_flags:
1300
1025
            mutter('hpss call:   %s', repr(args)[1:-1])
1301
1026
            base = getattr(self._medium_request._medium, 'base', None)
1302
1027
            if base is not None:
1303
1028
                mutter('             (to %s)', base)
1304
 
            self._request_start_time = osutils.timer_func()
 
1029
            self._request_start_time = time.time()
1305
1030
        self._write_protocol_version()
1306
 
        self._write_headers(self._headers)
 
1031
        self._write_headers(headers)
1307
1032
        self._write_structure(args)
1308
1033
        self._write_end()
1309
1034
        self._medium_request.finished_writing()
1310
1035
 
1311
 
    def call_with_body_bytes(self, args, body):
 
1036
    def call_with_body_bytes(self, args, body, headers=None):
1312
1037
        """Make a remote call of args with body bytes 'body'.
1313
1038
 
1314
1039
        After calling this, call read_response_tuple to find the result out.
1319
1044
            if path is not None:
1320
1045
                mutter('                  (to %s)', path)
1321
1046
            mutter('              %d bytes', len(body))
1322
 
            self._request_start_time = osutils.timer_func()
 
1047
            self._request_start_time = time.time()
1323
1048
        self._write_protocol_version()
1324
 
        self._write_headers(self._headers)
 
1049
        self._write_headers(headers)
1325
1050
        self._write_structure(args)
1326
1051
        self._write_prefixed_body(body)
1327
1052
        self._write_end()
1328
1053
        self._medium_request.finished_writing()
1329
1054
 
1330
 
    def call_with_body_readv_array(self, args, body):
 
1055
    def call_with_body_readv_array(self, args, body, headers=None):
1331
1056
        """Make a remote call with a readv array.
1332
1057
 
1333
1058
        The body is encoded with one line per readv offset pair. The numbers in
1338
1063
            path = getattr(self._medium_request._medium, '_path', None)
1339
1064
            if path is not None:
1340
1065
                mutter('                  (to %s)', path)
1341
 
            self._request_start_time = osutils.timer_func()
 
1066
            self._request_start_time = time.time()
1342
1067
        self._write_protocol_version()
1343
 
        self._write_headers(self._headers)
 
1068
        self._write_headers(headers)
1344
1069
        self._write_structure(args)
1345
1070
        readv_bytes = self._serialise_offsets(body)
1346
1071
        if 'hpss' in debug.debug_flags:
1349
1074
        self._write_end()
1350
1075
        self._medium_request.finished_writing()
1351
1076
 
1352
 
    def call_with_body_stream(self, args, stream):
1353
 
        if 'hpss' in debug.debug_flags:
1354
 
            mutter('hpss call w/body stream: %r', args)
1355
 
            path = getattr(self._medium_request._medium, '_path', None)
1356
 
            if path is not None:
1357
 
                mutter('                  (to %s)', path)
1358
 
            self._request_start_time = osutils.timer_func()
1359
 
        self._write_protocol_version()
1360
 
        self._write_headers(self._headers)
1361
 
        self._write_structure(args)
1362
 
        # TODO: notice if the server has sent an early error reply before we
1363
 
        #       have finished sending the stream.  We would notice at the end
1364
 
        #       anyway, but if the medium can deliver it early then it's good
1365
 
        #       to short-circuit the whole request...
1366
 
        for exc_info, part in _iter_with_errors(stream):
1367
 
            if exc_info is not None:
1368
 
                # Iterating the stream failed.  Cleanly abort the request.
1369
 
                self._write_error_status()
1370
 
                # Currently the client unconditionally sends ('error',) as the
1371
 
                # error args.
1372
 
                self._write_structure(('error',))
1373
 
                self._write_end()
1374
 
                self._medium_request.finished_writing()
1375
 
                raise exc_info[0], exc_info[1], exc_info[2]
1376
 
            else:
1377
 
                self._write_prefixed_body(part)
1378
 
                self.flush()
1379
 
        self._write_end()
1380
 
        self._medium_request.finished_writing()
1381