~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/smart/medium.py

  • Committer: Martin Pool
  • Date: 2007-06-21 04:27:47 UTC
  • mto: This revision was merged to the branch mainline in revision 2551.
  • Revision ID: mbp@sourcefrog.net-20070621042747-e3g0tdn8if750mv5
More commit specs

Show diffs side-by-side

added added

removed removed

Lines of Context:
27
27
import os
28
28
import socket
29
29
import sys
30
 
import urllib
31
30
 
32
 
from bzrlib.lazy_import import lazy_import
33
 
lazy_import(globals(), """
34
 
from bzrlib import (
35
 
    errors,
36
 
    osutils,
37
 
    symbol_versioning,
38
 
    urlutils,
 
31
from bzrlib import errors
 
32
from bzrlib.smart.protocol import (
 
33
    REQUEST_VERSION_TWO,
 
34
    SmartServerRequestProtocolOne,
 
35
    SmartServerRequestProtocolTwo,
39
36
    )
40
 
from bzrlib.smart import protocol
41
 
from bzrlib.transport import ssh
42
 
""")
43
 
 
44
 
 
45
 
# We must not read any more than 64k at a time so we don't risk "no buffer
46
 
# space available" errors on some platforms.  Windows in particular is likely
47
 
# to give error 10053 or 10055 if we read more than 64k from a socket.
48
 
_MAX_READ_SIZE = 64 * 1024
49
 
 
50
 
 
51
 
def _get_protocol_factory_for_bytes(bytes):
52
 
    """Determine the right protocol factory for 'bytes'.
53
 
 
54
 
    This will return an appropriate protocol factory depending on the version
55
 
    of the protocol being used, as determined by inspecting the given bytes.
56
 
    The bytes should have at least one newline byte (i.e. be a whole line),
57
 
    otherwise it's possible that a request will be incorrectly identified as
58
 
    version 1.
59
 
 
60
 
    Typical use would be::
61
 
 
62
 
         factory, unused_bytes = _get_protocol_factory_for_bytes(bytes)
63
 
         server_protocol = factory(transport, write_func, root_client_path)
64
 
         server_protocol.accept_bytes(unused_bytes)
65
 
 
66
 
    :param bytes: a str of bytes of the start of the request.
67
 
    :returns: 2-tuple of (protocol_factory, unused_bytes).  protocol_factory is
68
 
        a callable that takes three args: transport, write_func,
69
 
        root_client_path.  unused_bytes are any bytes that were not part of a
70
 
        protocol version marker.
71
 
    """
72
 
    if bytes.startswith(protocol.MESSAGE_VERSION_THREE):
73
 
        protocol_factory = protocol.build_server_protocol_three
74
 
        bytes = bytes[len(protocol.MESSAGE_VERSION_THREE):]
75
 
    elif bytes.startswith(protocol.REQUEST_VERSION_TWO):
76
 
        protocol_factory = protocol.SmartServerRequestProtocolTwo
77
 
        bytes = bytes[len(protocol.REQUEST_VERSION_TWO):]
78
 
    else:
79
 
        protocol_factory = protocol.SmartServerRequestProtocolOne
80
 
    return protocol_factory, bytes
81
 
 
82
 
 
83
 
def _get_line(read_bytes_func):
84
 
    """Read bytes using read_bytes_func until a newline byte.
85
 
    
86
 
    This isn't particularly efficient, so should only be used when the
87
 
    expected size of the line is quite short.
88
 
    
89
 
    :returns: a tuple of two strs: (line, excess)
90
 
    """
91
 
    newline_pos = -1
92
 
    bytes = ''
93
 
    while newline_pos == -1:
94
 
        new_bytes = read_bytes_func(1)
95
 
        bytes += new_bytes
96
 
        if new_bytes == '':
97
 
            # Ran out of bytes before receiving a complete line.
98
 
            return bytes, ''
99
 
        newline_pos = bytes.find('\n')
100
 
    line = bytes[:newline_pos+1]
101
 
    excess = bytes[newline_pos+1:]
102
 
    return line, excess
103
 
 
104
 
 
105
 
class SmartMedium(object):
106
 
    """Base class for smart protocol media, both client- and server-side."""
107
 
 
108
 
    def __init__(self):
109
 
        self._push_back_buffer = None
110
 
        
111
 
    def _push_back(self, bytes):
112
 
        """Return unused bytes to the medium, because they belong to the next
113
 
        request(s).
114
 
 
115
 
        This sets the _push_back_buffer to the given bytes.
116
 
        """
117
 
        if self._push_back_buffer is not None:
118
 
            raise AssertionError(
119
 
                "_push_back called when self._push_back_buffer is %r"
120
 
                % (self._push_back_buffer,))
121
 
        if bytes == '':
122
 
            return
123
 
        self._push_back_buffer = bytes
124
 
 
125
 
    def _get_push_back_buffer(self):
126
 
        if self._push_back_buffer == '':
127
 
            raise AssertionError(
128
 
                '%s._push_back_buffer should never be the empty string, '
129
 
                'which can be confused with EOF' % (self,))
130
 
        bytes = self._push_back_buffer
131
 
        self._push_back_buffer = None
132
 
        return bytes
133
 
 
134
 
    def read_bytes(self, desired_count):
135
 
        """Read some bytes from this medium.
136
 
 
137
 
        :returns: some bytes, possibly more or less than the number requested
138
 
            in 'desired_count' depending on the medium.
139
 
        """
140
 
        if self._push_back_buffer is not None:
141
 
            return self._get_push_back_buffer()
142
 
        bytes_to_read = min(desired_count, _MAX_READ_SIZE)
143
 
        return self._read_bytes(bytes_to_read)
144
 
 
145
 
    def _read_bytes(self, count):
146
 
        raise NotImplementedError(self._read_bytes)
147
 
 
148
 
    def _get_line(self):
149
 
        """Read bytes from this request's response until a newline byte.
150
 
        
151
 
        This isn't particularly efficient, so should only be used when the
152
 
        expected size of the line is quite short.
153
 
 
154
 
        :returns: a string of bytes ending in a newline (byte 0x0A).
155
 
        """
156
 
        line, excess = _get_line(self.read_bytes)
157
 
        self._push_back(excess)
158
 
        return line
159
 
 
160
 
 
161
 
class SmartServerStreamMedium(SmartMedium):
 
37
 
 
38
try:
 
39
    from bzrlib.transport import ssh
 
40
except errors.ParamikoNotPresent:
 
41
    # no paramiko.  SmartSSHClientMedium will break.
 
42
    pass
 
43
 
 
44
 
 
45
class SmartServerStreamMedium(object):
162
46
    """Handles smart commands coming over a stream.
163
47
 
164
48
    The stream may be a pipe connected to sshd, or a tcp socket, or an
169
53
 
170
54
    The server passes requests through to an underlying backing transport, 
171
55
    which will typically be a LocalTransport looking at the server's filesystem.
172
 
 
173
 
    :ivar _push_back_buffer: a str of bytes that have been read from the stream
174
 
        but not used yet, or None if there are no buffered bytes.  Subclasses
175
 
        should make sure to exhaust this buffer before reading more bytes from
176
 
        the stream.  See also the _push_back method.
177
56
    """
178
57
 
179
 
    def __init__(self, backing_transport, root_client_path='/'):
 
58
    def __init__(self, backing_transport):
180
59
        """Construct new server.
181
60
 
182
61
        :param backing_transport: Transport for the directory served.
183
62
        """
184
63
        # backing_transport could be passed to serve instead of __init__
185
64
        self.backing_transport = backing_transport
186
 
        self.root_client_path = root_client_path
187
65
        self.finished = False
188
 
        SmartMedium.__init__(self)
189
66
 
190
67
    def serve(self):
191
68
        """Serve requests until the client disconnects."""
209
86
 
210
87
        :returns: a SmartServerRequestProtocol.
211
88
        """
 
89
        # Identify the protocol version.
212
90
        bytes = self._get_line()
213
 
        protocol_factory, unused_bytes = _get_protocol_factory_for_bytes(bytes)
214
 
        protocol = protocol_factory(
215
 
            self.backing_transport, self._write_out, self.root_client_path)
216
 
        protocol.accept_bytes(unused_bytes)
 
91
        if bytes.startswith(REQUEST_VERSION_TWO):
 
92
            protocol_class = SmartServerRequestProtocolTwo
 
93
            bytes = bytes[len(REQUEST_VERSION_TWO):]
 
94
        else:
 
95
            protocol_class = SmartServerRequestProtocolOne
 
96
        protocol = protocol_class(self.backing_transport, self._write_out)
 
97
        protocol.accept_bytes(bytes)
217
98
        return protocol
218
99
 
219
100
    def _serve_one_request(self, protocol):
232
113
        """Called when an unhandled exception from the protocol occurs."""
233
114
        raise NotImplementedError(self.terminate_due_to_error)
234
115
 
235
 
    def _read_bytes(self, desired_count):
 
116
    def _get_bytes(self, desired_count):
236
117
        """Get some bytes from the medium.
237
118
 
238
119
        :param desired_count: number of bytes we want to read.
239
120
        """
240
 
        raise NotImplementedError(self._read_bytes)
 
121
        raise NotImplementedError(self._get_bytes)
 
122
 
 
123
    def _get_line(self):
 
124
        """Read bytes from this request's response until a newline byte.
 
125
        
 
126
        This isn't particularly efficient, so should only be used when the
 
127
        expected size of the line is quite short.
 
128
 
 
129
        :returns: a string of bytes ending in a newline (byte 0x0A).
 
130
        """
 
131
        # XXX: this duplicates SmartClientRequestProtocolOne._recv_tuple
 
132
        line = ''
 
133
        while not line or line[-1] != '\n':
 
134
            new_char = self._get_bytes(1)
 
135
            line += new_char
 
136
            if new_char == '':
 
137
                # Ran out of bytes before receiving a complete line.
 
138
                break
 
139
        return line
241
140
 
242
141
 
243
142
class SmartServerSocketStreamMedium(SmartServerStreamMedium):
244
143
 
245
 
    def __init__(self, sock, backing_transport, root_client_path='/'):
 
144
    def __init__(self, sock, backing_transport):
246
145
        """Constructor.
247
146
 
248
147
        :param sock: the socket the server will read from.  It will be put
249
148
            into blocking mode.
250
149
        """
251
 
        SmartServerStreamMedium.__init__(
252
 
            self, backing_transport, root_client_path=root_client_path)
 
150
        SmartServerStreamMedium.__init__(self, backing_transport)
 
151
        self.push_back = ''
253
152
        sock.setblocking(True)
254
153
        self.socket = sock
255
154
 
256
155
    def _serve_one_request_unguarded(self, protocol):
257
156
        while protocol.next_read_size():
258
 
            # We can safely try to read large chunks.  If there is less data
259
 
            # than _MAX_READ_SIZE ready, the socket wil just return a short
260
 
            # read immediately rather than block.
261
 
            bytes = self.read_bytes(_MAX_READ_SIZE)
262
 
            if bytes == '':
263
 
                self.finished = True
264
 
                return
265
 
            protocol.accept_bytes(bytes)
 
157
            if self.push_back:
 
158
                protocol.accept_bytes(self.push_back)
 
159
                self.push_back = ''
 
160
            else:
 
161
                bytes = self._get_bytes(4096)
 
162
                if bytes == '':
 
163
                    self.finished = True
 
164
                    return
 
165
                protocol.accept_bytes(bytes)
266
166
        
267
 
        self._push_back(protocol.unused_data)
 
167
        self.push_back = protocol.excess_buffer
268
168
 
269
 
    def _read_bytes(self, desired_count):
 
169
    def _get_bytes(self, desired_count):
270
170
        # We ignore the desired_count because on sockets it's more efficient to
271
 
        # read large chunks (of _MAX_READ_SIZE bytes) at a time.
272
 
        return self.socket.recv(_MAX_READ_SIZE)
273
 
 
 
171
        # read 4k at a time.
 
172
        return self.socket.recv(4096)
 
173
    
274
174
    def terminate_due_to_error(self):
 
175
        """Called when an unhandled exception from the protocol occurs."""
275
176
        # TODO: This should log to a server log file, but no such thing
276
177
        # exists yet.  Andrew Bennetts 2006-09-29.
277
178
        self.socket.close()
278
179
        self.finished = True
279
180
 
280
181
    def _write_out(self, bytes):
281
 
        osutils.send_all(self.socket, bytes)
 
182
        self.socket.sendall(bytes)
282
183
 
283
184
 
284
185
class SmartServerPipeStreamMedium(SmartServerStreamMedium):
303
204
 
304
205
    def _serve_one_request_unguarded(self, protocol):
305
206
        while True:
306
 
            # We need to be careful not to read past the end of the current
307
 
            # request, or else the read from the pipe will block, so we use
308
 
            # protocol.next_read_size().
309
207
            bytes_to_read = protocol.next_read_size()
310
208
            if bytes_to_read == 0:
311
209
                # Finished serving this request.
312
210
                self._out.flush()
313
211
                return
314
 
            bytes = self.read_bytes(bytes_to_read)
 
212
            bytes = self._get_bytes(bytes_to_read)
315
213
            if bytes == '':
316
214
                # Connection has been closed.
317
215
                self.finished = True
319
217
                return
320
218
            protocol.accept_bytes(bytes)
321
219
 
322
 
    def _read_bytes(self, desired_count):
 
220
    def _get_bytes(self, desired_count):
323
221
        return self._in.read(desired_count)
324
222
 
325
223
    def terminate_due_to_error(self):
439
337
        return self._read_bytes(count)
440
338
 
441
339
    def _read_bytes(self, count):
442
 
        """Helper for SmartClientMediumRequest.read_bytes.
 
340
        """Helper for read_bytes.
443
341
 
444
342
        read_bytes checks the state of the request to determing if bytes
445
343
        should be read. After that it hands off to _read_bytes to do the
446
344
        actual read.
447
 
        
448
 
        By default this forwards to self._medium.read_bytes because we are
449
 
        operating on the medium's stream.
450
345
        """
451
 
        return self._medium.read_bytes(count)
 
346
        raise NotImplementedError(self._read_bytes)
452
347
 
453
348
    def read_line(self):
454
 
        line = self._read_line()
455
 
        if not line.endswith('\n'):
456
 
            # end of file encountered reading from server
457
 
            raise errors.ConnectionReset(
458
 
                "please check connectivity and permissions",
459
 
                "(and try -Dhpss if further diagnosis is required)")
460
 
        return line
461
 
 
462
 
    def _read_line(self):
463
 
        """Helper for SmartClientMediumRequest.read_line.
 
349
        """Read bytes from this request's response until a newline byte.
464
350
        
465
 
        By default this forwards to self._medium._get_line because we are
466
 
        operating on the medium's stream.
 
351
        This isn't particularly efficient, so should only be used when the
 
352
        expected size of the line is quite short.
 
353
 
 
354
        :returns: a string of bytes ending in a newline (byte 0x0A).
467
355
        """
468
 
        return self._medium._get_line()
469
 
 
470
 
 
471
 
class SmartClientMedium(SmartMedium):
 
356
        # XXX: this duplicates SmartClientRequestProtocolOne._recv_tuple
 
357
        line = ''
 
358
        while not line or line[-1] != '\n':
 
359
            new_char = self.read_bytes(1)
 
360
            line += new_char
 
361
            if new_char == '':
 
362
                raise errors.SmartProtocolError(
 
363
                    'unexpected end of file reading from server')
 
364
        return line
 
365
 
 
366
 
 
367
class SmartClientMedium(object):
472
368
    """Smart client is a medium for sending smart protocol requests over."""
473
369
 
474
 
    def __init__(self, base):
475
 
        super(SmartClientMedium, self).__init__()
476
 
        self.base = base
477
 
        self._protocol_version_error = None
478
 
        self._protocol_version = None
479
 
        self._done_hello = False
480
 
        # Be optimistic: we assume the remote end can accept new remote
481
 
        # requests until we get an error saying otherwise.
482
 
        # _remote_version_is_before tracks the bzr version the remote side
483
 
        # can be based on what we've seen so far.
484
 
        self._remote_version_is_before = None
485
 
 
486
 
    def _is_remote_before(self, version_tuple):
487
 
        """Is it possible the remote side supports RPCs for a given version?
488
 
 
489
 
        Typical use::
490
 
 
491
 
            needed_version = (1, 2)
492
 
            if medium._is_remote_before(needed_version):
493
 
                fallback_to_pre_1_2_rpc()
494
 
            else:
495
 
                try:
496
 
                    do_1_2_rpc()
497
 
                except UnknownSmartMethod:
498
 
                    medium._remember_remote_is_before(needed_version)
499
 
                    fallback_to_pre_1_2_rpc()
500
 
 
501
 
        :seealso: _remember_remote_is_before
502
 
        """
503
 
        if self._remote_version_is_before is None:
504
 
            # So far, the remote side seems to support everything
505
 
            return False
506
 
        return version_tuple >= self._remote_version_is_before
507
 
 
508
 
    def _remember_remote_is_before(self, version_tuple):
509
 
        """Tell this medium that the remote side is older the given version.
510
 
 
511
 
        :seealso: _is_remote_before
512
 
        """
513
 
        if (self._remote_version_is_before is not None and
514
 
            version_tuple > self._remote_version_is_before):
515
 
            raise AssertionError(
516
 
                "_remember_remote_is_before(%r) called, but "
517
 
                "_remember_remote_is_before(%r) was called previously."
518
 
                % (version_tuple, self._remote_version_is_before))
519
 
        self._remote_version_is_before = version_tuple
520
 
 
521
 
    def protocol_version(self):
522
 
        """Find out if 'hello' smart request works."""
523
 
        if self._protocol_version_error is not None:
524
 
            raise self._protocol_version_error
525
 
        if not self._done_hello:
526
 
            try:
527
 
                medium_request = self.get_request()
528
 
                # Send a 'hello' request in protocol version one, for maximum
529
 
                # backwards compatibility.
530
 
                client_protocol = protocol.SmartClientRequestProtocolOne(medium_request)
531
 
                client_protocol.query_version()
532
 
                self._done_hello = True
533
 
            except errors.SmartProtocolError, e:
534
 
                # Cache the error, just like we would cache a successful
535
 
                # result.
536
 
                self._protocol_version_error = e
537
 
                raise
538
 
        return '2'
539
 
 
540
 
    def should_probe(self):
541
 
        """Should RemoteBzrDirFormat.probe_transport send a smart request on
542
 
        this medium?
543
 
 
544
 
        Some transports are unambiguously smart-only; there's no need to check
545
 
        if the transport is able to carry smart requests, because that's all
546
 
        it is for.  In those cases, this method should return False.
547
 
 
548
 
        But some HTTP transports can sometimes fail to carry smart requests,
549
 
        but still be usuable for accessing remote bzrdirs via plain file
550
 
        accesses.  So for those transports, their media should return True here
551
 
        so that RemoteBzrDirFormat can determine if it is appropriate for that
552
 
        transport.
553
 
        """
554
 
        return False
555
 
 
556
370
    def disconnect(self):
557
371
        """If this medium maintains a persistent connection, close it.
558
372
        
559
373
        The default implementation does nothing.
560
374
        """
561
375
        
562
 
    def remote_path_from_transport(self, transport):
563
 
        """Convert transport into a path suitable for using in a request.
564
 
        
565
 
        Note that the resulting remote path doesn't encode the host name or
566
 
        anything but path, so it is only safe to use it in requests sent over
567
 
        the medium from the matching transport.
568
 
        """
569
 
        medium_base = urlutils.join(self.base, '/')
570
 
        rel_url = urlutils.relative_url(medium_base, transport.base)
571
 
        return urllib.unquote(rel_url)
572
 
 
573
376
 
574
377
class SmartClientStreamMedium(SmartClientMedium):
575
378
    """Stream based medium common class.
580
383
    receive bytes.
581
384
    """
582
385
 
583
 
    def __init__(self, base):
584
 
        SmartClientMedium.__init__(self, base)
 
386
    def __init__(self):
585
387
        self._current_request = None
586
388
 
587
389
    def accept_bytes(self, bytes):
609
411
        """
610
412
        return SmartClientStreamMediumRequest(self)
611
413
 
 
414
    def read_bytes(self, count):
 
415
        return self._read_bytes(count)
 
416
 
612
417
 
613
418
class SmartSimplePipesClientMedium(SmartClientStreamMedium):
614
419
    """A client medium using simple pipes.
616
421
    This client does not manage the pipes: it assumes they will always be open.
617
422
    """
618
423
 
619
 
    def __init__(self, readable_pipe, writeable_pipe, base):
620
 
        SmartClientStreamMedium.__init__(self, base)
 
424
    def __init__(self, readable_pipe, writeable_pipe):
 
425
        SmartClientStreamMedium.__init__(self)
621
426
        self._readable_pipe = readable_pipe
622
427
        self._writeable_pipe = writeable_pipe
623
428
 
638
443
    """A client medium using SSH."""
639
444
    
640
445
    def __init__(self, host, port=None, username=None, password=None,
641
 
            base=None, vendor=None, bzr_remote_path=None):
 
446
            vendor=None):
642
447
        """Creates a client that will connect on the first use.
643
448
        
644
449
        :param vendor: An optional override for the ssh vendor to use. See
645
450
            bzrlib.transport.ssh for details on ssh vendors.
646
451
        """
647
 
        SmartClientStreamMedium.__init__(self, base)
 
452
        SmartClientStreamMedium.__init__(self)
648
453
        self._connected = False
649
454
        self._host = host
650
455
        self._password = password
654
459
        self._ssh_connection = None
655
460
        self._vendor = vendor
656
461
        self._write_to = None
657
 
        self._bzr_remote_path = bzr_remote_path
658
 
        if self._bzr_remote_path is None:
659
 
            symbol_versioning.warn(
660
 
                'bzr_remote_path is required as of bzr 0.92',
661
 
                DeprecationWarning, stacklevel=2)
662
 
            self._bzr_remote_path = os.environ.get('BZR_REMOTE_PATH', 'bzr')
663
462
 
664
463
    def _accept_bytes(self, bytes):
665
464
        """See SmartClientStreamMedium.accept_bytes."""
679
478
        """Connect this medium if not already connected."""
680
479
        if self._connected:
681
480
            return
 
481
        executable = os.environ.get('BZR_REMOTE_PATH', 'bzr')
682
482
        if self._vendor is None:
683
483
            vendor = ssh._get_ssh_vendor()
684
484
        else:
685
485
            vendor = self._vendor
686
486
        self._ssh_connection = vendor.connect_ssh(self._username,
687
487
                self._password, self._host, self._port,
688
 
                command=[self._bzr_remote_path, 'serve', '--inet',
689
 
                         '--directory=/', '--allow-writes'])
 
488
                command=[executable, 'serve', '--inet', '--directory=/',
 
489
                         '--allow-writes'])
690
490
        self._read_from, self._write_to = \
691
491
            self._ssh_connection.get_filelike_channels()
692
492
        self._connected = True
699
499
        """See SmartClientStreamMedium.read_bytes."""
700
500
        if not self._connected:
701
501
            raise errors.MediumNotConnected(self)
702
 
        bytes_to_read = min(count, _MAX_READ_SIZE)
703
 
        return self._read_from.read(bytes_to_read)
704
 
 
705
 
 
706
 
# Port 4155 is the default port for bzr://, registered with IANA.
707
 
BZR_DEFAULT_INTERFACE = '0.0.0.0'
708
 
BZR_DEFAULT_PORT = 4155
 
502
        return self._read_from.read(count)
709
503
 
710
504
 
711
505
class SmartTCPClientMedium(SmartClientStreamMedium):
712
506
    """A client medium using TCP."""
713
507
    
714
 
    def __init__(self, host, port, base):
 
508
    def __init__(self, host, port):
715
509
        """Creates a client that will connect on the first use."""
716
 
        SmartClientStreamMedium.__init__(self, base)
 
510
        SmartClientStreamMedium.__init__(self)
717
511
        self._connected = False
718
512
        self._host = host
719
513
        self._port = port
722
516
    def _accept_bytes(self, bytes):
723
517
        """See SmartClientMedium.accept_bytes."""
724
518
        self._ensure_connection()
725
 
        osutils.send_all(self._socket, bytes)
 
519
        self._socket.sendall(bytes)
726
520
 
727
521
    def disconnect(self):
728
522
        """See SmartClientMedium.disconnect()."""
738
532
            return
739
533
        self._socket = socket.socket()
740
534
        self._socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
741
 
        if self._port is None:
742
 
            port = BZR_DEFAULT_PORT
743
 
        else:
744
 
            port = int(self._port)
745
 
        try:
746
 
            self._socket.connect((self._host, port))
747
 
        except socket.error, err:
748
 
            # socket errors either have a (string) or (errno, string) as their
749
 
            # args.
750
 
            if type(err.args) is str:
751
 
                err_msg = err.args
752
 
            else:
753
 
                err_msg = err.args[1]
 
535
        result = self._socket.connect_ex((self._host, int(self._port)))
 
536
        if result:
754
537
            raise errors.ConnectionError("failed to connect to %s:%d: %s" %
755
 
                    (self._host, port, err_msg))
 
538
                    (self._host, self._port, os.strerror(result)))
756
539
        self._connected = True
757
540
 
758
541
    def _flush(self):
766
549
        """See SmartClientMedium.read_bytes."""
767
550
        if not self._connected:
768
551
            raise errors.MediumNotConnected(self)
769
 
        # We ignore the desired_count because on sockets it's more efficient to
770
 
        # read large chunks (of _MAX_READ_SIZE bytes) at a time.
771
 
        return self._socket.recv(_MAX_READ_SIZE)
 
552
        return self._socket.recv(count)
772
553
 
773
554
 
774
555
class SmartClientStreamMediumRequest(SmartClientMediumRequest):
799
580
        This clears the _current_request on self._medium to allow a new 
800
581
        request to be created.
801
582
        """
802
 
        if self._medium._current_request is not self:
803
 
            raise AssertionError()
 
583
        assert self._medium._current_request is self
804
584
        self._medium._current_request = None
805
585
        
806
586
    def _finished_writing(self):
810
590
        """
811
591
        self._medium._flush()
812
592
 
 
593
    def _read_bytes(self, count):
 
594
        """See SmartClientMediumRequest._read_bytes.
 
595
        
 
596
        This forwards to self._medium._read_bytes because we are operating
 
597
        on the mediums stream.
 
598
        """
 
599
        return self._medium._read_bytes(count)
 
600