/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/medium.py

Merge from bzr.dev, resolving conflicts.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2011 Canonical Ltd
 
1
# Copyright (C) 2006 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
"""The 'medium' layer for the smart servers and clients.
18
18
 
21
21
 
22
22
Media carry the bytes of the requests somehow (e.g. via TCP, wrapped in HTTP, or
23
23
over SSH), and pass them to and from the protocol logic.  See the overview in
24
 
breezy/transport/smart/__init__.py.
 
24
bzrlib/transport/smart/__init__.py.
25
25
"""
26
26
 
27
 
from __future__ import absolute_import
28
 
 
29
 
import errno
30
 
import io
31
27
import os
32
 
import sys
33
 
import time
34
 
 
35
 
import breezy
36
 
from ...lazy_import import lazy_import
37
 
lazy_import(globals(), """
38
 
import select
39
28
import socket
40
 
import thread
41
 
import weakref
42
 
 
43
 
from breezy import (
44
 
    debug,
45
 
    trace,
46
 
    transport,
47
 
    ui,
48
 
    urlutils,
49
 
    )
50
 
from breezy.i18n import gettext
51
 
from breezy.bzr.smart import client, protocol, request, signals, vfs
52
 
from breezy.transport import ssh
53
 
""")
54
 
from ... import (
55
 
    errors,
56
 
    osutils,
57
 
    )
58
 
 
59
 
# Throughout this module buffer size parameters are either limited to be at
60
 
# most _MAX_READ_SIZE, or are ignored and _MAX_READ_SIZE is used instead.
61
 
# For this module's purposes, MAX_SOCKET_CHUNK is a reasonable size for reads
62
 
# from non-sockets as well.
63
 
_MAX_READ_SIZE = osutils.MAX_SOCKET_CHUNK
64
 
 
65
 
 
66
 
class HpssVfsRequestNotAllowed(errors.BzrError):
67
 
 
68
 
    _fmt = ("VFS requests over the smart server are not allowed. Encountered: "
69
 
            "%(method)s, %(arguments)s.")
70
 
 
71
 
    def __init__(self, method, arguments):
72
 
        self.method = method
73
 
        self.arguments = arguments
74
 
 
75
 
 
76
 
def _get_protocol_factory_for_bytes(bytes):
77
 
    """Determine the right protocol factory for 'bytes'.
78
 
 
79
 
    This will return an appropriate protocol factory depending on the version
80
 
    of the protocol being used, as determined by inspecting the given bytes.
81
 
    The bytes should have at least one newline byte (i.e. be a whole line),
82
 
    otherwise it's possible that a request will be incorrectly identified as
83
 
    version 1.
84
 
 
85
 
    Typical use would be::
86
 
 
87
 
         factory, unused_bytes = _get_protocol_factory_for_bytes(bytes)
88
 
         server_protocol = factory(transport, write_func, root_client_path)
89
 
         server_protocol.accept_bytes(unused_bytes)
90
 
 
91
 
    :param bytes: a str of bytes of the start of the request.
92
 
    :returns: 2-tuple of (protocol_factory, unused_bytes).  protocol_factory is
93
 
        a callable that takes three args: transport, write_func,
94
 
        root_client_path.  unused_bytes are any bytes that were not part of a
95
 
        protocol version marker.
96
 
    """
97
 
    if bytes.startswith(protocol.MESSAGE_VERSION_THREE):
98
 
        protocol_factory = protocol.build_server_protocol_three
99
 
        bytes = bytes[len(protocol.MESSAGE_VERSION_THREE):]
100
 
    elif bytes.startswith(protocol.REQUEST_VERSION_TWO):
101
 
        protocol_factory = protocol.SmartServerRequestProtocolTwo
102
 
        bytes = bytes[len(protocol.REQUEST_VERSION_TWO):]
103
 
    else:
104
 
        protocol_factory = protocol.SmartServerRequestProtocolOne
105
 
    return protocol_factory, bytes
106
 
 
107
 
 
108
 
def _get_line(read_bytes_func):
109
 
    """Read bytes using read_bytes_func until a newline byte.
110
 
 
111
 
    This isn't particularly efficient, so should only be used when the
112
 
    expected size of the line is quite short.
113
 
 
114
 
    :returns: a tuple of two strs: (line, excess)
115
 
    """
116
 
    newline_pos = -1
117
 
    bytes = b''
118
 
    while newline_pos == -1:
119
 
        new_bytes = read_bytes_func(1)
120
 
        bytes += new_bytes
121
 
        if new_bytes == b'':
122
 
            # Ran out of bytes before receiving a complete line.
123
 
            return bytes, b''
124
 
        newline_pos = bytes.find(b'\n')
125
 
    line = bytes[:newline_pos+1]
126
 
    excess = bytes[newline_pos+1:]
127
 
    return line, excess
128
 
 
129
 
 
130
 
class SmartMedium(object):
131
 
    """Base class for smart protocol media, both client- and server-side."""
132
 
 
133
 
    def __init__(self):
134
 
        self._push_back_buffer = None
135
 
 
136
 
    def _push_back(self, data):
137
 
        """Return unused bytes to the medium, because they belong to the next
138
 
        request(s).
139
 
 
140
 
        This sets the _push_back_buffer to the given bytes.
141
 
        """
142
 
        if not isinstance(data, bytes):
143
 
            raise TypeError(data)
144
 
        if self._push_back_buffer is not None:
145
 
            raise AssertionError(
146
 
                "_push_back called when self._push_back_buffer is %r"
147
 
                % (self._push_back_buffer,))
148
 
        if data == b'':
149
 
            return
150
 
        self._push_back_buffer = data
151
 
 
152
 
    def _get_push_back_buffer(self):
153
 
        if self._push_back_buffer == b'':
154
 
            raise AssertionError(
155
 
                '%s._push_back_buffer should never be the empty string, '
156
 
                'which can be confused with EOF' % (self,))
157
 
        bytes = self._push_back_buffer
158
 
        self._push_back_buffer = None
159
 
        return bytes
160
 
 
161
 
    def read_bytes(self, desired_count):
162
 
        """Read some bytes from this medium.
163
 
 
164
 
        :returns: some bytes, possibly more or less than the number requested
165
 
            in 'desired_count' depending on the medium.
166
 
        """
167
 
        if self._push_back_buffer is not None:
168
 
            return self._get_push_back_buffer()
169
 
        bytes_to_read = min(desired_count, _MAX_READ_SIZE)
170
 
        return self._read_bytes(bytes_to_read)
171
 
 
172
 
    def _read_bytes(self, count):
173
 
        raise NotImplementedError(self._read_bytes)
174
 
 
175
 
    def _get_line(self):
176
 
        """Read bytes from this request's response until a newline byte.
177
 
 
178
 
        This isn't particularly efficient, so should only be used when the
179
 
        expected size of the line is quite short.
180
 
 
181
 
        :returns: a string of bytes ending in a newline (byte 0x0A).
182
 
        """
183
 
        line, excess = _get_line(self.read_bytes)
184
 
        self._push_back(excess)
185
 
        return line
186
 
 
187
 
    def _report_activity(self, bytes, direction):
188
 
        """Notify that this medium has activity.
189
 
 
190
 
        Implementations should call this from all methods that actually do IO.
191
 
        Be careful that it's not called twice, if one method is implemented on
192
 
        top of another.
193
 
 
194
 
        :param bytes: Number of bytes read or written.
195
 
        :param direction: 'read' or 'write' or None.
196
 
        """
197
 
        ui.ui_factory.report_transport_activity(self, bytes, direction)
198
 
 
199
 
 
200
 
_bad_file_descriptor = (errno.EBADF,)
201
 
if sys.platform == 'win32':
202
 
    # Given on Windows if you pass a closed socket to select.select. Probably
203
 
    # also given if you pass a file handle to select.
204
 
    WSAENOTSOCK = 10038
205
 
    _bad_file_descriptor += (WSAENOTSOCK,)
206
 
 
207
 
 
208
 
class SmartServerStreamMedium(SmartMedium):
 
29
 
 
30
from bzrlib import errors
 
31
from bzrlib.smart import protocol
 
32
try:
 
33
    from bzrlib.transport import ssh
 
34
except errors.ParamikoNotPresent:
 
35
    # no paramiko.  SmartSSHClientMedium will break.
 
36
    pass
 
37
 
 
38
 
 
39
class SmartServerStreamMedium(object):
209
40
    """Handles smart commands coming over a stream.
210
41
 
211
42
    The stream may be a pipe connected to sshd, or a tcp socket, or an
214
45
    One instance is created for each connected client; it can serve multiple
215
46
    requests in the lifetime of the connection.
216
47
 
217
 
    The server passes requests through to an underlying backing transport,
 
48
    The server passes requests through to an underlying backing transport, 
218
49
    which will typically be a LocalTransport looking at the server's filesystem.
219
 
 
220
 
    :ivar _push_back_buffer: a str of bytes that have been read from the stream
221
 
        but not used yet, or None if there are no buffered bytes.  Subclasses
222
 
        should make sure to exhaust this buffer before reading more bytes from
223
 
        the stream.  See also the _push_back method.
224
50
    """
225
51
 
226
 
    _timer = time.time
227
 
 
228
 
    def __init__(self, backing_transport, root_client_path='/', timeout=None):
 
52
    def __init__(self, backing_transport):
229
53
        """Construct new server.
230
54
 
231
55
        :param backing_transport: Transport for the directory served.
232
56
        """
233
57
        # backing_transport could be passed to serve instead of __init__
234
58
        self.backing_transport = backing_transport
235
 
        self.root_client_path = root_client_path
236
59
        self.finished = False
237
 
        if timeout is None:
238
 
            raise AssertionError('You must supply a timeout.')
239
 
        self._client_timeout = timeout
240
 
        self._client_poll_timeout = min(timeout / 10.0, 1.0)
241
 
        SmartMedium.__init__(self)
242
60
 
243
61
    def serve(self):
244
62
        """Serve requests until the client disconnects."""
247
65
        from sys import stderr
248
66
        try:
249
67
            while not self.finished:
250
 
                server_protocol = self._build_protocol()
 
68
                server_protocol = protocol.SmartServerRequestProtocolOne(
 
69
                    self.backing_transport, self._write_out)
251
70
                self._serve_one_request(server_protocol)
252
 
        except errors.ConnectionTimeout as e:
253
 
            trace.note('%s' % (e,))
254
 
            trace.log_exception_quietly()
255
 
            self._disconnect_client()
256
 
            # We reported it, no reason to make a big fuss.
257
 
            return
258
 
        except Exception as e:
 
71
        except Exception, e:
259
72
            stderr.write("%s terminating on exception %s\n" % (self, e))
260
73
            raise
261
 
        self._disconnect_client()
262
 
 
263
 
    def _stop_gracefully(self):
264
 
        """When we finish this message, stop looking for more."""
265
 
        trace.mutter('Stopping %s' % (self,))
266
 
        self.finished = True
267
 
 
268
 
    def _disconnect_client(self):
269
 
        """Close the current connection. We stopped due to a timeout/etc."""
270
 
        # The default implementation is a no-op, because that is all we used to
271
 
        # do when disconnecting from a client. I suppose we never had the
272
 
        # *server* initiate a disconnect, before
273
 
 
274
 
    def _wait_for_bytes_with_timeout(self, timeout_seconds):
275
 
        """Wait for more bytes to be read, but timeout if none available.
276
 
 
277
 
        This allows us to detect idle connections, and stop trying to read from
278
 
        them, without setting the socket itself to non-blocking. This also
279
 
        allows us to specify when we watch for idle timeouts.
280
 
 
281
 
        :return: Did we timeout? (True if we timed out, False if there is data
282
 
            to be read)
283
 
        """
284
 
        raise NotImplementedError(self._wait_for_bytes_with_timeout)
285
 
 
286
 
    def _build_protocol(self):
287
 
        """Identifies the version of the incoming request, and returns an
288
 
        a protocol object that can interpret it.
289
 
 
290
 
        If more bytes than the version prefix of the request are read, they will
291
 
        be fed into the protocol before it is returned.
292
 
 
293
 
        :returns: a SmartServerRequestProtocol.
294
 
        """
295
 
        self._wait_for_bytes_with_timeout(self._client_timeout)
296
 
        if self.finished:
297
 
            # We're stopping, so don't try to do any more work
298
 
            return None
299
 
        bytes = self._get_line()
300
 
        protocol_factory, unused_bytes = _get_protocol_factory_for_bytes(bytes)
301
 
        protocol = protocol_factory(
302
 
            self.backing_transport, self._write_out, self.root_client_path)
303
 
        protocol.accept_bytes(unused_bytes)
304
 
        return protocol
305
 
 
306
 
    def _wait_on_descriptor(self, fd, timeout_seconds):
307
 
        """select() on a file descriptor, waiting for nonblocking read()
308
 
 
309
 
        This will raise a ConnectionTimeout exception if we do not get a
310
 
        readable handle before timeout_seconds.
311
 
        :return: None
312
 
        """
313
 
        t_end = self._timer() + timeout_seconds
314
 
        poll_timeout = min(timeout_seconds, self._client_poll_timeout)
315
 
        rs = xs = None
316
 
        while not rs and not xs and self._timer() < t_end:
317
 
            if self.finished:
318
 
                return
319
 
            try:
320
 
                rs, _, xs = select.select([fd], [], [fd], poll_timeout)
321
 
            except (select.error, socket.error) as e:
322
 
                err = getattr(e, 'errno', None)
323
 
                if err is None and getattr(e, 'args', None) is not None:
324
 
                    # select.error doesn't have 'errno', it just has args[0]
325
 
                    err = e.args[0]
326
 
                if err in _bad_file_descriptor:
327
 
                    return # Not a socket indicates read() will fail
328
 
                elif err == errno.EINTR:
329
 
                    # Interrupted, keep looping.
330
 
                    continue
331
 
                raise
332
 
            except ValueError:
333
 
                return  # Socket may already be closed
334
 
        if rs or xs:
335
 
            return
336
 
        raise errors.ConnectionTimeout('disconnecting client after %.1f seconds'
337
 
                                       % (timeout_seconds,))
338
74
 
339
75
    def _serve_one_request(self, protocol):
340
76
        """Read one request from input, process, send back a response.
341
 
 
 
77
        
342
78
        :param protocol: a SmartServerRequestProtocol.
343
79
        """
344
 
        if protocol is None:
345
 
            return
346
80
        try:
347
81
            self._serve_one_request_unguarded(protocol)
348
82
        except KeyboardInterrupt:
349
83
            raise
350
 
        except Exception as e:
 
84
        except Exception, e:
351
85
            self.terminate_due_to_error()
352
86
 
353
87
    def terminate_due_to_error(self):
354
88
        """Called when an unhandled exception from the protocol occurs."""
355
89
        raise NotImplementedError(self.terminate_due_to_error)
356
90
 
357
 
    def _read_bytes(self, desired_count):
358
 
        """Get some bytes from the medium.
359
 
 
360
 
        :param desired_count: number of bytes we want to read.
361
 
        """
362
 
        raise NotImplementedError(self._read_bytes)
363
 
 
364
91
 
365
92
class SmartServerSocketStreamMedium(SmartServerStreamMedium):
366
93
 
367
 
    def __init__(self, sock, backing_transport, root_client_path='/',
368
 
                 timeout=None):
 
94
    def __init__(self, sock, backing_transport):
369
95
        """Constructor.
370
96
 
371
97
        :param sock: the socket the server will read from.  It will be put
372
98
            into blocking mode.
373
99
        """
374
 
        SmartServerStreamMedium.__init__(
375
 
            self, backing_transport, root_client_path=root_client_path,
376
 
            timeout=timeout)
 
100
        SmartServerStreamMedium.__init__(self, backing_transport)
 
101
        self.push_back = ''
377
102
        sock.setblocking(True)
378
103
        self.socket = sock
379
 
        # Get the getpeername now, as we might be closed later when we care.
380
 
        try:
381
 
            self._client_info = sock.getpeername()
382
 
        except socket.error:
383
 
            self._client_info = '<unknown>'
384
 
 
385
 
    def __str__(self):
386
 
        return '%s(client=%s)' % (self.__class__.__name__, self._client_info)
387
 
 
388
 
    def __repr__(self):
389
 
        return '%s.%s(client=%s)' % (self.__module__, self.__class__.__name__,
390
 
            self._client_info)
391
104
 
392
105
    def _serve_one_request_unguarded(self, protocol):
393
106
        while protocol.next_read_size():
394
 
            # We can safely try to read large chunks.  If there is less data
395
 
            # than MAX_SOCKET_CHUNK ready, the socket will just return a
396
 
            # short read immediately rather than block.
397
 
            bytes = self.read_bytes(osutils.MAX_SOCKET_CHUNK)
398
 
            if bytes == b'':
399
 
                self.finished = True
400
 
                return
401
 
            protocol.accept_bytes(bytes)
402
 
 
403
 
        self._push_back(protocol.unused_data)
404
 
 
405
 
    def _disconnect_client(self):
406
 
        """Close the current connection. We stopped due to a timeout/etc."""
407
 
        self.socket.close()
408
 
 
409
 
    def _wait_for_bytes_with_timeout(self, timeout_seconds):
410
 
        """Wait for more bytes to be read, but timeout if none available.
411
 
 
412
 
        This allows us to detect idle connections, and stop trying to read from
413
 
        them, without setting the socket itself to non-blocking. This also
414
 
        allows us to specify when we watch for idle timeouts.
415
 
 
416
 
        :return: None, this will raise ConnectionTimeout if we time out before
417
 
            data is available.
418
 
        """
419
 
        return self._wait_on_descriptor(self.socket, timeout_seconds)
420
 
 
421
 
    def _read_bytes(self, desired_count):
422
 
        return osutils.read_bytes_from_socket(
423
 
            self.socket, self._report_activity)
424
 
 
 
107
            if self.push_back:
 
108
                protocol.accept_bytes(self.push_back)
 
109
                self.push_back = ''
 
110
            else:
 
111
                bytes = self.socket.recv(4096)
 
112
                if bytes == '':
 
113
                    self.finished = True
 
114
                    return
 
115
                protocol.accept_bytes(bytes)
 
116
        
 
117
        self.push_back = protocol.excess_buffer
 
118
    
425
119
    def terminate_due_to_error(self):
 
120
        """Called when an unhandled exception from the protocol occurs."""
426
121
        # TODO: This should log to a server log file, but no such thing
427
122
        # exists yet.  Andrew Bennetts 2006-09-29.
428
123
        self.socket.close()
429
124
        self.finished = True
430
125
 
431
126
    def _write_out(self, bytes):
432
 
        tstart = osutils.timer_func()
433
 
        osutils.send_all(self.socket, bytes, self._report_activity)
434
 
        if 'hpss' in debug.debug_flags:
435
 
            thread_id = thread.get_ident()
436
 
            trace.mutter('%12s: [%s] %d bytes to the socket in %.3fs'
437
 
                         % ('wrote', thread_id, len(bytes),
438
 
                            osutils.timer_func() - tstart))
 
127
        self.socket.sendall(bytes)
439
128
 
440
129
 
441
130
class SmartServerPipeStreamMedium(SmartServerStreamMedium):
442
131
 
443
 
    def __init__(self, in_file, out_file, backing_transport, timeout=None):
 
132
    def __init__(self, in_file, out_file, backing_transport):
444
133
        """Construct new server.
445
134
 
446
135
        :param in_file: Python file from which requests can be read.
447
136
        :param out_file: Python file to write responses.
448
137
        :param backing_transport: Transport for the directory served.
449
138
        """
450
 
        SmartServerStreamMedium.__init__(self, backing_transport,
451
 
            timeout=timeout)
452
 
        if sys.platform == 'win32':
453
 
            # force binary mode for files
454
 
            import msvcrt
455
 
            for f in (in_file, out_file):
456
 
                fileno = getattr(f, 'fileno', None)
457
 
                if fileno:
458
 
                    msvcrt.setmode(fileno(), os.O_BINARY)
 
139
        SmartServerStreamMedium.__init__(self, backing_transport)
459
140
        self._in = in_file
460
141
        self._out = out_file
461
142
 
462
 
    def serve(self):
463
 
        """See SmartServerStreamMedium.serve"""
464
 
        # This is the regular serve, except it adds signal trapping for soft
465
 
        # shutdown.
466
 
        stop_gracefully = self._stop_gracefully
467
 
        signals.register_on_hangup(id(self), stop_gracefully)
468
 
        try:
469
 
            return super(SmartServerPipeStreamMedium, self).serve()
470
 
        finally:
471
 
            signals.unregister_on_hangup(id(self))
472
 
 
473
143
    def _serve_one_request_unguarded(self, protocol):
474
144
        while True:
475
 
            # We need to be careful not to read past the end of the current
476
 
            # request, or else the read from the pipe will block, so we use
477
 
            # protocol.next_read_size().
478
145
            bytes_to_read = protocol.next_read_size()
479
146
            if bytes_to_read == 0:
480
147
                # Finished serving this request.
481
148
                self._out.flush()
482
149
                return
483
 
            bytes = self.read_bytes(bytes_to_read)
484
 
            if bytes == b'':
 
150
            bytes = self._in.read(bytes_to_read)
 
151
            if bytes == '':
485
152
                # Connection has been closed.
486
153
                self.finished = True
487
154
                self._out.flush()
488
155
                return
489
156
            protocol.accept_bytes(bytes)
490
157
 
491
 
    def _disconnect_client(self):
492
 
        self._in.close()
493
 
        self._out.flush()
494
 
        self._out.close()
495
 
 
496
 
    def _wait_for_bytes_with_timeout(self, timeout_seconds):
497
 
        """Wait for more bytes to be read, but timeout if none available.
498
 
 
499
 
        This allows us to detect idle connections, and stop trying to read from
500
 
        them, without setting the socket itself to non-blocking. This also
501
 
        allows us to specify when we watch for idle timeouts.
502
 
 
503
 
        :return: None, this will raise ConnectionTimeout if we time out before
504
 
            data is available.
505
 
        """
506
 
        if (getattr(self._in, 'fileno', None) is None
507
 
            or sys.platform == 'win32'):
508
 
            # You can't select() file descriptors on Windows.
509
 
            return
510
 
        try:
511
 
            return self._wait_on_descriptor(self._in, timeout_seconds)
512
 
        except io.UnsupportedOperation:
513
 
            return
514
 
 
515
 
    def _read_bytes(self, desired_count):
516
 
        return self._in.read(desired_count)
517
 
 
518
158
    def terminate_due_to_error(self):
519
159
        # TODO: This should log to a server log file, but no such thing
520
160
        # exists yet.  Andrew Bennetts 2006-09-29.
538
178
    request.finished_reading()
539
179
 
540
180
    It is up to the individual SmartClientMedium whether multiple concurrent
541
 
    requests can exist. See SmartClientMedium.get_request to obtain instances
542
 
    of SmartClientMediumRequest, and the concrete Medium you are using for
 
181
    requests can exist. See SmartClientMedium.get_request to obtain instances 
 
182
    of SmartClientMediumRequest, and the concrete Medium you are using for 
543
183
    details on concurrency and pipelining.
544
184
    """
545
185
 
554
194
    def accept_bytes(self, bytes):
555
195
        """Accept bytes for inclusion in this request.
556
196
 
557
 
        This method may not be called after finished_writing() has been
 
197
        This method may not be be called after finished_writing() has been
558
198
        called.  It depends upon the Medium whether or not the bytes will be
559
199
        immediately transmitted. Message based Mediums will tend to buffer the
560
200
        bytes until finished_writing() is called.
591
231
    def _finished_reading(self):
592
232
        """Helper for finished_reading.
593
233
 
594
 
        finished_reading checks the state of the request to determine if
 
234
        finished_reading checks the state of the request to determine if 
595
235
        finished_reading is allowed, and if it is hands off to _finished_reading
596
236
        to perform the action.
597
237
        """
611
251
    def _finished_writing(self):
612
252
        """Helper for finished_writing.
613
253
 
614
 
        finished_writing checks the state of the request to determine if
 
254
        finished_writing checks the state of the request to determine if 
615
255
        finished_writing is allowed, and if it is hands off to _finished_writing
616
256
        to perform the action.
617
257
        """
622
262
 
623
263
        This method will block and wait for count bytes to be read. It may not
624
264
        be invoked until finished_writing() has been called - this is to ensure
625
 
        a message-based approach to requests, for compatibility with message
 
265
        a message-based approach to requests, for compatability with message
626
266
        based mediums like HTTP.
627
267
        """
628
268
        if self._state == "writing":
632
272
        return self._read_bytes(count)
633
273
 
634
274
    def _read_bytes(self, count):
635
 
        """Helper for SmartClientMediumRequest.read_bytes.
 
275
        """Helper for read_bytes.
636
276
 
637
277
        read_bytes checks the state of the request to determing if bytes
638
278
        should be read. After that it hands off to _read_bytes to do the
639
279
        actual read.
640
 
 
641
 
        By default this forwards to self._medium.read_bytes because we are
642
 
        operating on the medium's stream.
643
 
        """
644
 
        return self._medium.read_bytes(count)
645
 
 
646
 
    def read_line(self):
647
 
        line = self._read_line()
648
 
        if not line.endswith(b'\n'):
649
 
            # end of file encountered reading from server
650
 
            raise errors.ConnectionReset(
651
 
                "Unexpected end of message. Please check connectivity "
652
 
                "and permissions, and report a bug if problems persist.")
653
 
        return line
654
 
 
655
 
    def _read_line(self):
656
 
        """Helper for SmartClientMediumRequest.read_line.
657
 
 
658
 
        By default this forwards to self._medium._get_line because we are
659
 
        operating on the medium's stream.
660
 
        """
661
 
        return self._medium._get_line()
662
 
 
663
 
 
664
 
class _VfsRefuser(object):
665
 
    """An object that refuses all VFS requests.
666
 
 
667
 
    """
668
 
 
669
 
    def __init__(self):
670
 
        client._SmartClient.hooks.install_named_hook(
671
 
            'call', self.check_vfs, 'vfs refuser')
672
 
 
673
 
    def check_vfs(self, params):
674
 
        try:
675
 
            request_method = request.request_handlers.get(params.method)
676
 
        except KeyError:
677
 
            # A method we don't know about doesn't count as a VFS method.
678
 
            return
679
 
        if issubclass(request_method, vfs.VfsRequest):
680
 
            raise HpssVfsRequestNotAllowed(params.method, params.args)
681
 
 
682
 
 
683
 
class _DebugCounter(object):
684
 
    """An object that counts the HPSS calls made to each client medium.
685
 
 
686
 
    When a medium is garbage-collected, or failing that when
687
 
    breezy.global_state exits, the total number of calls made on that medium
688
 
    are reported via trace.note.
689
 
    """
690
 
 
691
 
    def __init__(self):
692
 
        self.counts = weakref.WeakKeyDictionary()
693
 
        client._SmartClient.hooks.install_named_hook(
694
 
            'call', self.increment_call_count, 'hpss call counter')
695
 
        breezy.get_global_state().cleanups.add_cleanup(self.flush_all)
696
 
 
697
 
    def track(self, medium):
698
 
        """Start tracking calls made to a medium.
699
 
 
700
 
        This only keeps a weakref to the medium, so shouldn't affect the
701
 
        medium's lifetime.
702
 
        """
703
 
        medium_repr = repr(medium)
704
 
        # Add this medium to the WeakKeyDictionary
705
 
        self.counts[medium] = dict(count=0, vfs_count=0,
706
 
                                   medium_repr=medium_repr)
707
 
        # Weakref callbacks are fired in reverse order of their association
708
 
        # with the referenced object.  So we add a weakref *after* adding to
709
 
        # the WeakKeyDict so that we can report the value from it before the
710
 
        # entry is removed by the WeakKeyDict's own callback.
711
 
        ref = weakref.ref(medium, self.done)
712
 
 
713
 
    def increment_call_count(self, params):
714
 
        # Increment the count in the WeakKeyDictionary
715
 
        value = self.counts[params.medium]
716
 
        value['count'] += 1
717
 
        try:
718
 
            request_method = request.request_handlers.get(params.method)
719
 
        except KeyError:
720
 
            # A method we don't know about doesn't count as a VFS method.
721
 
            return
722
 
        if issubclass(request_method, vfs.VfsRequest):
723
 
            value['vfs_count'] += 1
724
 
 
725
 
    def done(self, ref):
726
 
        value = self.counts[ref]
727
 
        count, vfs_count, medium_repr = (
728
 
            value['count'], value['vfs_count'], value['medium_repr'])
729
 
        # In case this callback is invoked for the same ref twice (by the
730
 
        # weakref callback and by the atexit function), set the call count back
731
 
        # to 0 so this item won't be reported twice.
732
 
        value['count'] = 0
733
 
        value['vfs_count'] = 0
734
 
        if count != 0:
735
 
            trace.note(gettext('HPSS calls: {0} ({1} vfs) {2}').format(
736
 
                       count, vfs_count, medium_repr))
737
 
 
738
 
    def flush_all(self):
739
 
        for ref in list(self.counts.keys()):
740
 
            self.done(ref)
741
 
 
742
 
_debug_counter = None
743
 
_vfs_refuser = None
744
 
 
745
 
 
746
 
class SmartClientMedium(SmartMedium):
 
280
        """
 
281
        raise NotImplementedError(self._read_bytes)
 
282
 
 
283
 
 
284
class SmartClientMedium(object):
747
285
    """Smart client is a medium for sending smart protocol requests over."""
748
286
 
749
 
    def __init__(self, base):
750
 
        super(SmartClientMedium, self).__init__()
751
 
        self.base = base
752
 
        self._protocol_version_error = None
753
 
        self._protocol_version = None
754
 
        self._done_hello = False
755
 
        # Be optimistic: we assume the remote end can accept new remote
756
 
        # requests until we get an error saying otherwise.
757
 
        # _remote_version_is_before tracks the bzr version the remote side
758
 
        # can be based on what we've seen so far.
759
 
        self._remote_version_is_before = None
760
 
        # Install debug hook function if debug flag is set.
761
 
        if 'hpss' in debug.debug_flags:
762
 
            global _debug_counter
763
 
            if _debug_counter is None:
764
 
                _debug_counter = _DebugCounter()
765
 
            _debug_counter.track(self)
766
 
        if 'hpss_client_no_vfs' in debug.debug_flags:
767
 
            global _vfs_refuser
768
 
            if _vfs_refuser is None:
769
 
                _vfs_refuser = _VfsRefuser()
770
 
 
771
 
    def _is_remote_before(self, version_tuple):
772
 
        """Is it possible the remote side supports RPCs for a given version?
773
 
 
774
 
        Typical use::
775
 
 
776
 
            needed_version = (1, 2)
777
 
            if medium._is_remote_before(needed_version):
778
 
                fallback_to_pre_1_2_rpc()
779
 
            else:
780
 
                try:
781
 
                    do_1_2_rpc()
782
 
                except UnknownSmartMethod:
783
 
                    medium._remember_remote_is_before(needed_version)
784
 
                    fallback_to_pre_1_2_rpc()
785
 
 
786
 
        :seealso: _remember_remote_is_before
787
 
        """
788
 
        if self._remote_version_is_before is None:
789
 
            # So far, the remote side seems to support everything
790
 
            return False
791
 
        return version_tuple >= self._remote_version_is_before
792
 
 
793
 
    def _remember_remote_is_before(self, version_tuple):
794
 
        """Tell this medium that the remote side is older the given version.
795
 
 
796
 
        :seealso: _is_remote_before
797
 
        """
798
 
        if (self._remote_version_is_before is not None and
799
 
            version_tuple > self._remote_version_is_before):
800
 
            # We have been told that the remote side is older than some version
801
 
            # which is newer than a previously supplied older-than version.
802
 
            # This indicates that some smart verb call is not guarded
803
 
            # appropriately (it should simply not have been tried).
804
 
            trace.mutter(
805
 
                "_remember_remote_is_before(%r) called, but "
806
 
                "_remember_remote_is_before(%r) was called previously."
807
 
                , version_tuple, self._remote_version_is_before)
808
 
            if 'hpss' in debug.debug_flags:
809
 
                ui.ui_factory.show_warning(
810
 
                    "_remember_remote_is_before(%r) called, but "
811
 
                    "_remember_remote_is_before(%r) was called previously."
812
 
                    % (version_tuple, self._remote_version_is_before))
813
 
            return
814
 
        self._remote_version_is_before = version_tuple
815
 
 
816
 
    def protocol_version(self):
817
 
        """Find out if 'hello' smart request works."""
818
 
        if self._protocol_version_error is not None:
819
 
            raise self._protocol_version_error
820
 
        if not self._done_hello:
821
 
            try:
822
 
                medium_request = self.get_request()
823
 
                # Send a 'hello' request in protocol version one, for maximum
824
 
                # backwards compatibility.
825
 
                client_protocol = protocol.SmartClientRequestProtocolOne(medium_request)
826
 
                client_protocol.query_version()
827
 
                self._done_hello = True
828
 
            except errors.SmartProtocolError as e:
829
 
                # Cache the error, just like we would cache a successful
830
 
                # result.
831
 
                self._protocol_version_error = e
832
 
                raise
833
 
        return '2'
834
 
 
835
 
    def should_probe(self):
836
 
        """Should RemoteBzrDirFormat.probe_transport send a smart request on
837
 
        this medium?
838
 
 
839
 
        Some transports are unambiguously smart-only; there's no need to check
840
 
        if the transport is able to carry smart requests, because that's all
841
 
        it is for.  In those cases, this method should return False.
842
 
 
843
 
        But some HTTP transports can sometimes fail to carry smart requests,
844
 
        but still be usuable for accessing remote bzrdirs via plain file
845
 
        accesses.  So for those transports, their media should return True here
846
 
        so that RemoteBzrDirFormat can determine if it is appropriate for that
847
 
        transport.
848
 
        """
849
 
        return False
850
 
 
851
287
    def disconnect(self):
852
288
        """If this medium maintains a persistent connection, close it.
853
 
 
 
289
        
854
290
        The default implementation does nothing.
855
291
        """
856
 
 
857
 
    def remote_path_from_transport(self, transport):
858
 
        """Convert transport into a path suitable for using in a request.
859
 
 
860
 
        Note that the resulting remote path doesn't encode the host name or
861
 
        anything but path, so it is only safe to use it in requests sent over
862
 
        the medium from the matching transport.
863
 
        """
864
 
        medium_base = urlutils.join(self.base, '/')
865
 
        rel_url = urlutils.relative_url(medium_base, transport.base)
866
 
        return urlutils.unquote(rel_url)
867
 
 
 
292
        
868
293
 
869
294
class SmartClientStreamMedium(SmartClientMedium):
870
295
    """Stream based medium common class.
875
300
    receive bytes.
876
301
    """
877
302
 
878
 
    def __init__(self, base):
879
 
        SmartClientMedium.__init__(self, base)
 
303
    def __init__(self):
880
304
        self._current_request = None
881
305
 
882
306
    def accept_bytes(self, bytes):
890
314
 
891
315
    def _flush(self):
892
316
        """Flush the output stream.
893
 
 
 
317
        
894
318
        This method is used by the SmartClientStreamMediumRequest to ensure that
895
319
        all data for a request is sent, to avoid long timeouts or deadlocks.
896
320
        """
904
328
        """
905
329
        return SmartClientStreamMediumRequest(self)
906
330
 
907
 
    def reset(self):
908
 
        """We have been disconnected, reset current state.
909
 
 
910
 
        This resets things like _current_request and connected state.
911
 
        """
912
 
        self.disconnect()
913
 
        self._current_request = None
 
331
    def read_bytes(self, count):
 
332
        return self._read_bytes(count)
914
333
 
915
334
 
916
335
class SmartSimplePipesClientMedium(SmartClientStreamMedium):
917
336
    """A client medium using simple pipes.
918
 
 
 
337
    
919
338
    This client does not manage the pipes: it assumes they will always be open.
920
339
    """
921
340
 
922
 
    def __init__(self, readable_pipe, writeable_pipe, base):
923
 
        SmartClientStreamMedium.__init__(self, base)
 
341
    def __init__(self, readable_pipe, writeable_pipe):
 
342
        SmartClientStreamMedium.__init__(self)
924
343
        self._readable_pipe = readable_pipe
925
344
        self._writeable_pipe = writeable_pipe
926
345
 
927
 
    def _accept_bytes(self, data):
 
346
    def _accept_bytes(self, bytes):
928
347
        """See SmartClientStreamMedium.accept_bytes."""
929
 
        try:
930
 
            self._writeable_pipe.write(data)
931
 
        except IOError as e:
932
 
            if e.errno in (errno.EINVAL, errno.EPIPE):
933
 
                raise errors.ConnectionReset(
934
 
                    "Error trying to write to subprocess", e)
935
 
            raise
936
 
        self._report_activity(len(data), 'write')
 
348
        self._writeable_pipe.write(bytes)
937
349
 
938
350
    def _flush(self):
939
351
        """See SmartClientStreamMedium._flush()."""
940
 
        # Note: If flush were to fail, we'd like to raise ConnectionReset, etc.
941
 
        #       However, testing shows that even when the child process is
942
 
        #       gone, this doesn't error.
943
352
        self._writeable_pipe.flush()
944
353
 
945
354
    def _read_bytes(self, count):
946
355
        """See SmartClientStreamMedium._read_bytes."""
947
 
        bytes_to_read = min(count, _MAX_READ_SIZE)
948
 
        data = self._readable_pipe.read(bytes_to_read)
949
 
        self._report_activity(len(data), 'read')
950
 
        return data
951
 
 
952
 
 
953
 
class SSHParams(object):
954
 
    """A set of parameters for starting a remote bzr via SSH."""
955
 
 
 
356
        return self._readable_pipe.read(count)
 
357
 
 
358
 
 
359
class SmartSSHClientMedium(SmartClientStreamMedium):
 
360
    """A client medium using SSH."""
 
361
    
956
362
    def __init__(self, host, port=None, username=None, password=None,
957
 
            bzr_remote_path='bzr'):
958
 
        self.host = host
959
 
        self.port = port
960
 
        self.username = username
961
 
        self.password = password
962
 
        self.bzr_remote_path = bzr_remote_path
963
 
 
964
 
 
965
 
class SmartSSHClientMedium(SmartClientStreamMedium):
966
 
    """A client medium using SSH.
967
 
 
968
 
    It delegates IO to a SmartSimplePipesClientMedium or
969
 
    SmartClientAlreadyConnectedSocketMedium (depending on platform).
970
 
    """
971
 
 
972
 
    def __init__(self, base, ssh_params, vendor=None):
 
363
            vendor=None):
973
364
        """Creates a client that will connect on the first use.
974
 
 
975
 
        :param ssh_params: A SSHParams instance.
 
365
        
976
366
        :param vendor: An optional override for the ssh vendor to use. See
977
 
            breezy.transport.ssh for details on ssh vendors.
 
367
            bzrlib.transport.ssh for details on ssh vendors.
978
368
        """
979
 
        self._real_medium = None
980
 
        self._ssh_params = ssh_params
981
 
        # for the benefit of progress making a short description of this
982
 
        # transport
983
 
        self._scheme = 'bzr+ssh'
984
 
        # SmartClientStreamMedium stores the repr of this object in its
985
 
        # _DebugCounter so we have to store all the values used in our repr
986
 
        # method before calling the super init.
987
 
        SmartClientStreamMedium.__init__(self, base)
 
369
        SmartClientStreamMedium.__init__(self)
 
370
        self._connected = False
 
371
        self._host = host
 
372
        self._password = password
 
373
        self._port = port
 
374
        self._username = username
 
375
        self._read_from = None
 
376
        self._ssh_connection = None
988
377
        self._vendor = vendor
989
 
        self._ssh_connection = None
990
 
 
991
 
    def __repr__(self):
992
 
        if self._ssh_params.port is None:
993
 
            maybe_port = ''
994
 
        else:
995
 
            maybe_port = ':%s' % self._ssh_params.port
996
 
        if self._ssh_params.username is None:
997
 
            maybe_user = ''
998
 
        else:
999
 
            maybe_user = '%s@' % self._ssh_params.username
1000
 
        return "%s(%s://%s%s%s/)" % (
1001
 
            self.__class__.__name__,
1002
 
            self._scheme,
1003
 
            maybe_user,
1004
 
            self._ssh_params.host,
1005
 
            maybe_port)
 
378
        self._write_to = None
1006
379
 
1007
380
    def _accept_bytes(self, bytes):
1008
381
        """See SmartClientStreamMedium.accept_bytes."""
1009
382
        self._ensure_connection()
1010
 
        self._real_medium.accept_bytes(bytes)
 
383
        self._write_to.write(bytes)
1011
384
 
1012
385
    def disconnect(self):
1013
386
        """See SmartClientMedium.disconnect()."""
1014
 
        if self._real_medium is not None:
1015
 
            self._real_medium.disconnect()
1016
 
            self._real_medium = None
1017
 
        if self._ssh_connection is not None:
1018
 
            self._ssh_connection.close()
1019
 
            self._ssh_connection = None
 
387
        if not self._connected:
 
388
            return
 
389
        self._read_from.close()
 
390
        self._write_to.close()
 
391
        self._ssh_connection.close()
 
392
        self._connected = False
1020
393
 
1021
394
    def _ensure_connection(self):
1022
395
        """Connect this medium if not already connected."""
1023
 
        if self._real_medium is not None:
 
396
        if self._connected:
1024
397
            return
 
398
        executable = os.environ.get('BZR_REMOTE_PATH', 'bzr')
1025
399
        if self._vendor is None:
1026
400
            vendor = ssh._get_ssh_vendor()
1027
401
        else:
1028
402
            vendor = self._vendor
1029
 
        self._ssh_connection = vendor.connect_ssh(self._ssh_params.username,
1030
 
                self._ssh_params.password, self._ssh_params.host,
1031
 
                self._ssh_params.port,
1032
 
                command=[self._ssh_params.bzr_remote_path, 'serve', '--inet',
1033
 
                         '--directory=/', '--allow-writes'])
1034
 
        io_kind, io_object = self._ssh_connection.get_sock_or_pipes()
1035
 
        if io_kind == 'socket':
1036
 
            self._real_medium = SmartClientAlreadyConnectedSocketMedium(
1037
 
                self.base, io_object)
1038
 
        elif io_kind == 'pipes':
1039
 
            read_from, write_to = io_object
1040
 
            self._real_medium = SmartSimplePipesClientMedium(
1041
 
                read_from, write_to, self.base)
1042
 
        else:
1043
 
            raise AssertionError(
1044
 
                "Unexpected io_kind %r from %r"
1045
 
                % (io_kind, self._ssh_connection))
1046
 
        for hook in transport.Transport.hooks["post_connect"]:
1047
 
            hook(self)
 
403
        self._ssh_connection = vendor.connect_ssh(self._username,
 
404
                self._password, self._host, self._port,
 
405
                command=[executable, 'serve', '--inet', '--directory=/',
 
406
                         '--allow-writes'])
 
407
        self._read_from, self._write_to = \
 
408
            self._ssh_connection.get_filelike_channels()
 
409
        self._connected = True
1048
410
 
1049
411
    def _flush(self):
1050
412
        """See SmartClientStreamMedium._flush()."""
1051
 
        self._real_medium._flush()
 
413
        self._write_to.flush()
1052
414
 
1053
415
    def _read_bytes(self, count):
1054
416
        """See SmartClientStreamMedium.read_bytes."""
1055
 
        if self._real_medium is None:
 
417
        if not self._connected:
1056
418
            raise errors.MediumNotConnected(self)
1057
 
        return self._real_medium.read_bytes(count)
1058
 
 
1059
 
 
1060
 
# Port 4155 is the default port for bzr://, registered with IANA.
1061
 
BZR_DEFAULT_INTERFACE = None
1062
 
BZR_DEFAULT_PORT = 4155
1063
 
 
1064
 
 
1065
 
class SmartClientSocketMedium(SmartClientStreamMedium):
1066
 
    """A client medium using a socket.
1067
 
 
1068
 
    This class isn't usable directly.  Use one of its subclasses instead.
1069
 
    """
1070
 
 
1071
 
    def __init__(self, base):
1072
 
        SmartClientStreamMedium.__init__(self, base)
 
419
        return self._read_from.read(count)
 
420
 
 
421
 
 
422
class SmartTCPClientMedium(SmartClientStreamMedium):
 
423
    """A client medium using TCP."""
 
424
    
 
425
    def __init__(self, host, port):
 
426
        """Creates a client that will connect on the first use."""
 
427
        SmartClientStreamMedium.__init__(self)
 
428
        self._connected = False
 
429
        self._host = host
 
430
        self._port = port
1073
431
        self._socket = None
1074
 
        self._connected = False
1075
432
 
1076
433
    def _accept_bytes(self, bytes):
1077
434
        """See SmartClientMedium.accept_bytes."""
1078
435
        self._ensure_connection()
1079
 
        osutils.send_all(self._socket, bytes, self._report_activity)
 
436
        self._socket.sendall(bytes)
 
437
 
 
438
    def disconnect(self):
 
439
        """See SmartClientMedium.disconnect()."""
 
440
        if not self._connected:
 
441
            return
 
442
        self._socket.close()
 
443
        self._socket = None
 
444
        self._connected = False
1080
445
 
1081
446
    def _ensure_connection(self):
1082
447
        """Connect this medium if not already connected."""
1083
 
        raise NotImplementedError(self._ensure_connection)
 
448
        if self._connected:
 
449
            return
 
450
        self._socket = socket.socket()
 
451
        self._socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
 
452
        result = self._socket.connect_ex((self._host, int(self._port)))
 
453
        if result:
 
454
            raise errors.ConnectionError("failed to connect to %s:%d: %s" %
 
455
                    (self._host, self._port, os.strerror(result)))
 
456
        self._connected = True
1084
457
 
1085
458
    def _flush(self):
1086
459
        """See SmartClientStreamMedium._flush().
1087
 
 
1088
 
        For sockets we do no flushing. For TCP sockets we may want to turn off
1089
 
        TCP_NODELAY and add a means to do a flush, but that can be done in the
1090
 
        future.
 
460
        
 
461
        For TCP we do no flushing. We may want to turn off TCP_NODELAY and 
 
462
        add a means to do a flush, but that can be done in the future.
1091
463
        """
1092
464
 
1093
465
    def _read_bytes(self, count):
1094
466
        """See SmartClientMedium.read_bytes."""
1095
467
        if not self._connected:
1096
468
            raise errors.MediumNotConnected(self)
1097
 
        return osutils.read_bytes_from_socket(
1098
 
            self._socket, self._report_activity)
1099
 
 
1100
 
    def disconnect(self):
1101
 
        """See SmartClientMedium.disconnect()."""
1102
 
        if not self._connected:
1103
 
            return
1104
 
        self._socket.close()
1105
 
        self._socket = None
1106
 
        self._connected = False
1107
 
 
1108
 
 
1109
 
class SmartTCPClientMedium(SmartClientSocketMedium):
1110
 
    """A client medium that creates a TCP connection."""
1111
 
 
1112
 
    def __init__(self, host, port, base):
1113
 
        """Creates a client that will connect on the first use."""
1114
 
        SmartClientSocketMedium.__init__(self, base)
1115
 
        self._host = host
1116
 
        self._port = port
1117
 
 
1118
 
    def _ensure_connection(self):
1119
 
        """Connect this medium if not already connected."""
1120
 
        if self._connected:
1121
 
            return
1122
 
        if self._port is None:
1123
 
            port = BZR_DEFAULT_PORT
1124
 
        else:
1125
 
            port = int(self._port)
1126
 
        try:
1127
 
            sockaddrs = socket.getaddrinfo(self._host, port, socket.AF_UNSPEC,
1128
 
                socket.SOCK_STREAM, 0, 0)
1129
 
        except socket.gaierror as xxx_todo_changeme:
1130
 
            (err_num, err_msg) = xxx_todo_changeme.args
1131
 
            raise errors.ConnectionError("failed to lookup %s:%d: %s" %
1132
 
                    (self._host, port, err_msg))
1133
 
        # Initialize err in case there are no addresses returned:
1134
 
        last_err = socket.error("no address found for %s" % self._host)
1135
 
        for (family, socktype, proto, canonname, sockaddr) in sockaddrs:
1136
 
            try:
1137
 
                self._socket = socket.socket(family, socktype, proto)
1138
 
                self._socket.setsockopt(socket.IPPROTO_TCP,
1139
 
                                        socket.TCP_NODELAY, 1)
1140
 
                self._socket.connect(sockaddr)
1141
 
            except socket.error as err:
1142
 
                if self._socket is not None:
1143
 
                    self._socket.close()
1144
 
                self._socket = None
1145
 
                last_err = err
1146
 
                continue
1147
 
            break
1148
 
        if self._socket is None:
1149
 
            # socket errors either have a (string) or (errno, string) as their
1150
 
            # args.
1151
 
            if isinstance(last_err.args, str):
1152
 
                err_msg = last_err.args
1153
 
            else:
1154
 
                err_msg = last_err.args[1]
1155
 
            raise errors.ConnectionError("failed to connect to %s:%d: %s" %
1156
 
                    (self._host, port, err_msg))
1157
 
        self._connected = True
1158
 
        for hook in transport.Transport.hooks["post_connect"]:
1159
 
            hook(self)
1160
 
 
1161
 
 
1162
 
class SmartClientAlreadyConnectedSocketMedium(SmartClientSocketMedium):
1163
 
    """A client medium for an already connected socket.
1164
 
    
1165
 
    Note that this class will assume it "owns" the socket, so it will close it
1166
 
    when its disconnect method is called.
1167
 
    """
1168
 
 
1169
 
    def __init__(self, base, sock):
1170
 
        SmartClientSocketMedium.__init__(self, base)
1171
 
        self._socket = sock
1172
 
        self._connected = True
1173
 
 
1174
 
    def _ensure_connection(self):
1175
 
        # Already connected, by definition!  So nothing to do.
1176
 
        pass
 
469
        return self._socket.recv(count)
1177
470
 
1178
471
 
1179
472
class SmartClientStreamMediumRequest(SmartClientMediumRequest):
1192
485
 
1193
486
    def _accept_bytes(self, bytes):
1194
487
        """See SmartClientMediumRequest._accept_bytes.
1195
 
 
 
488
        
1196
489
        This forwards to self._medium._accept_bytes because we are operating
1197
490
        on the mediums stream.
1198
491
        """
1201
494
    def _finished_reading(self):
1202
495
        """See SmartClientMediumRequest._finished_reading.
1203
496
 
1204
 
        This clears the _current_request on self._medium to allow a new
 
497
        This clears the _current_request on self._medium to allow a new 
1205
498
        request to be created.
1206
499
        """
1207
 
        if self._medium._current_request is not self:
1208
 
            raise AssertionError()
 
500
        assert self._medium._current_request is self
1209
501
        self._medium._current_request = None
1210
 
 
 
502
        
1211
503
    def _finished_writing(self):
1212
504
        """See SmartClientMediumRequest._finished_writing.
1213
505
 
1214
506
        This invokes self._medium._flush to ensure all bytes are transmitted.
1215
507
        """
1216
508
        self._medium._flush()
 
509
 
 
510
    def _read_bytes(self, count):
 
511
        """See SmartClientMediumRequest._read_bytes.
 
512
        
 
513
        This forwards to self._medium._read_bytes because we are operating
 
514
        on the mediums stream.
 
515
        """
 
516
        return self._medium._read_bytes(count)
 
517