~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/smart/medium.py

  • Committer: Robert Collins
  • Date: 2007-04-19 02:27:44 UTC
  • mto: This revision was merged to the branch mainline in revision 2426.
  • Revision ID: robertc@robertcollins.net-20070419022744-pfdqz42kp1wizh43
``make docs`` now creates a man page at ``man1/bzr.1`` fixing bug 107388.
(Robert Collins)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006 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
"""The 'medium' layer for the smart servers and clients.
18
18
 
24
24
bzrlib/transport/smart/__init__.py.
25
25
"""
26
26
 
27
 
import errno
28
27
import os
29
28
import socket
30
29
import sys
31
 
import urllib
32
 
 
33
 
from bzrlib.lazy_import import lazy_import
34
 
lazy_import(globals(), """
35
 
import atexit
36
 
import thread
37
 
import weakref
38
 
 
39
 
from bzrlib import (
40
 
    debug,
41
 
    errors,
42
 
    symbol_versioning,
43
 
    trace,
44
 
    ui,
45
 
    urlutils,
46
 
    )
47
 
from bzrlib.smart import client, protocol, request, vfs
48
 
from bzrlib.transport import ssh
49
 
""")
50
 
#usually already imported, and getting IllegalScoperReplacer on it here.
51
 
from bzrlib import osutils
52
 
 
53
 
# We must not read any more than 64k at a time so we don't risk "no buffer
54
 
# space available" errors on some platforms.  Windows in particular is likely
55
 
# to give error 10053 or 10055 if we read more than 64k from a socket.
56
 
_MAX_READ_SIZE = 64 * 1024
57
 
 
58
 
 
59
 
def _get_protocol_factory_for_bytes(bytes):
60
 
    """Determine the right protocol factory for 'bytes'.
61
 
 
62
 
    This will return an appropriate protocol factory depending on the version
63
 
    of the protocol being used, as determined by inspecting the given bytes.
64
 
    The bytes should have at least one newline byte (i.e. be a whole line),
65
 
    otherwise it's possible that a request will be incorrectly identified as
66
 
    version 1.
67
 
 
68
 
    Typical use would be::
69
 
 
70
 
         factory, unused_bytes = _get_protocol_factory_for_bytes(bytes)
71
 
         server_protocol = factory(transport, write_func, root_client_path)
72
 
         server_protocol.accept_bytes(unused_bytes)
73
 
 
74
 
    :param bytes: a str of bytes of the start of the request.
75
 
    :returns: 2-tuple of (protocol_factory, unused_bytes).  protocol_factory is
76
 
        a callable that takes three args: transport, write_func,
77
 
        root_client_path.  unused_bytes are any bytes that were not part of a
78
 
        protocol version marker.
79
 
    """
80
 
    if bytes.startswith(protocol.MESSAGE_VERSION_THREE):
81
 
        protocol_factory = protocol.build_server_protocol_three
82
 
        bytes = bytes[len(protocol.MESSAGE_VERSION_THREE):]
83
 
    elif bytes.startswith(protocol.REQUEST_VERSION_TWO):
84
 
        protocol_factory = protocol.SmartServerRequestProtocolTwo
85
 
        bytes = bytes[len(protocol.REQUEST_VERSION_TWO):]
86
 
    else:
87
 
        protocol_factory = protocol.SmartServerRequestProtocolOne
88
 
    return protocol_factory, bytes
89
 
 
90
 
 
91
 
def _get_line(read_bytes_func):
92
 
    """Read bytes using read_bytes_func until a newline byte.
93
 
 
94
 
    This isn't particularly efficient, so should only be used when the
95
 
    expected size of the line is quite short.
96
 
 
97
 
    :returns: a tuple of two strs: (line, excess)
98
 
    """
99
 
    newline_pos = -1
100
 
    bytes = ''
101
 
    while newline_pos == -1:
102
 
        new_bytes = read_bytes_func(1)
103
 
        bytes += new_bytes
104
 
        if new_bytes == '':
105
 
            # Ran out of bytes before receiving a complete line.
106
 
            return bytes, ''
107
 
        newline_pos = bytes.find('\n')
108
 
    line = bytes[:newline_pos+1]
109
 
    excess = bytes[newline_pos+1:]
110
 
    return line, excess
111
 
 
112
 
 
113
 
class SmartMedium(object):
114
 
    """Base class for smart protocol media, both client- and server-side."""
115
 
 
116
 
    def __init__(self):
117
 
        self._push_back_buffer = None
118
 
 
119
 
    def _push_back(self, bytes):
120
 
        """Return unused bytes to the medium, because they belong to the next
121
 
        request(s).
122
 
 
123
 
        This sets the _push_back_buffer to the given bytes.
124
 
        """
125
 
        if self._push_back_buffer is not None:
126
 
            raise AssertionError(
127
 
                "_push_back called when self._push_back_buffer is %r"
128
 
                % (self._push_back_buffer,))
129
 
        if bytes == '':
130
 
            return
131
 
        self._push_back_buffer = bytes
132
 
 
133
 
    def _get_push_back_buffer(self):
134
 
        if self._push_back_buffer == '':
135
 
            raise AssertionError(
136
 
                '%s._push_back_buffer should never be the empty string, '
137
 
                'which can be confused with EOF' % (self,))
138
 
        bytes = self._push_back_buffer
139
 
        self._push_back_buffer = None
140
 
        return bytes
141
 
 
142
 
    def read_bytes(self, desired_count):
143
 
        """Read some bytes from this medium.
144
 
 
145
 
        :returns: some bytes, possibly more or less than the number requested
146
 
            in 'desired_count' depending on the medium.
147
 
        """
148
 
        if self._push_back_buffer is not None:
149
 
            return self._get_push_back_buffer()
150
 
        bytes_to_read = min(desired_count, _MAX_READ_SIZE)
151
 
        return self._read_bytes(bytes_to_read)
152
 
 
153
 
    def _read_bytes(self, count):
154
 
        raise NotImplementedError(self._read_bytes)
155
 
 
156
 
    def _get_line(self):
157
 
        """Read bytes from this request's response until a newline byte.
158
 
 
159
 
        This isn't particularly efficient, so should only be used when the
160
 
        expected size of the line is quite short.
161
 
 
162
 
        :returns: a string of bytes ending in a newline (byte 0x0A).
163
 
        """
164
 
        line, excess = _get_line(self.read_bytes)
165
 
        self._push_back(excess)
166
 
        return line
167
 
 
168
 
    def _report_activity(self, bytes, direction):
169
 
        """Notify that this medium has activity.
170
 
 
171
 
        Implementations should call this from all methods that actually do IO.
172
 
        Be careful that it's not called twice, if one method is implemented on
173
 
        top of another.
174
 
 
175
 
        :param bytes: Number of bytes read or written.
176
 
        :param direction: 'read' or 'write' or None.
177
 
        """
178
 
        ui.ui_factory.report_transport_activity(self, bytes, direction)
179
 
 
180
 
 
181
 
class SmartServerStreamMedium(SmartMedium):
 
30
from bzrlib import errors
 
31
from bzrlib.smart.protocol import SmartServerRequestProtocolOne
 
32
 
 
33
try:
 
34
    from bzrlib.transport import ssh
 
35
except errors.ParamikoNotPresent:
 
36
    # no paramiko.  SmartSSHClientMedium will break.
 
37
    pass
 
38
 
 
39
 
 
40
class SmartServerStreamMedium(object):
182
41
    """Handles smart commands coming over a stream.
183
42
 
184
43
    The stream may be a pipe connected to sshd, or a tcp socket, or an
187
46
    One instance is created for each connected client; it can serve multiple
188
47
    requests in the lifetime of the connection.
189
48
 
190
 
    The server passes requests through to an underlying backing transport,
 
49
    The server passes requests through to an underlying backing transport, 
191
50
    which will typically be a LocalTransport looking at the server's filesystem.
192
 
 
193
 
    :ivar _push_back_buffer: a str of bytes that have been read from the stream
194
 
        but not used yet, or None if there are no buffered bytes.  Subclasses
195
 
        should make sure to exhaust this buffer before reading more bytes from
196
 
        the stream.  See also the _push_back method.
197
51
    """
198
52
 
199
 
    def __init__(self, backing_transport, root_client_path='/'):
 
53
    def __init__(self, backing_transport):
200
54
        """Construct new server.
201
55
 
202
56
        :param backing_transport: Transport for the directory served.
203
57
        """
204
58
        # backing_transport could be passed to serve instead of __init__
205
59
        self.backing_transport = backing_transport
206
 
        self.root_client_path = root_client_path
207
60
        self.finished = False
208
 
        SmartMedium.__init__(self)
209
61
 
210
62
    def serve(self):
211
63
        """Serve requests until the client disconnects."""
214
66
        from sys import stderr
215
67
        try:
216
68
            while not self.finished:
217
 
                server_protocol = self._build_protocol()
218
 
                self._serve_one_request(server_protocol)
 
69
                protocol = SmartServerRequestProtocolOne(self.backing_transport,
 
70
                                                         self._write_out)
 
71
                self._serve_one_request(protocol)
219
72
        except Exception, e:
220
73
            stderr.write("%s terminating on exception %s\n" % (self, e))
221
74
            raise
222
75
 
223
 
    def _build_protocol(self):
224
 
        """Identifies the version of the incoming request, and returns an
225
 
        a protocol object that can interpret it.
226
 
 
227
 
        If more bytes than the version prefix of the request are read, they will
228
 
        be fed into the protocol before it is returned.
229
 
 
230
 
        :returns: a SmartServerRequestProtocol.
231
 
        """
232
 
        bytes = self._get_line()
233
 
        protocol_factory, unused_bytes = _get_protocol_factory_for_bytes(bytes)
234
 
        protocol = protocol_factory(
235
 
            self.backing_transport, self._write_out, self.root_client_path)
236
 
        protocol.accept_bytes(unused_bytes)
237
 
        return protocol
238
 
 
239
76
    def _serve_one_request(self, protocol):
240
77
        """Read one request from input, process, send back a response.
241
 
 
 
78
        
242
79
        :param protocol: a SmartServerRequestProtocol.
243
80
        """
244
81
        try:
252
89
        """Called when an unhandled exception from the protocol occurs."""
253
90
        raise NotImplementedError(self.terminate_due_to_error)
254
91
 
255
 
    def _read_bytes(self, desired_count):
256
 
        """Get some bytes from the medium.
257
 
 
258
 
        :param desired_count: number of bytes we want to read.
259
 
        """
260
 
        raise NotImplementedError(self._read_bytes)
261
 
 
262
92
 
263
93
class SmartServerSocketStreamMedium(SmartServerStreamMedium):
264
94
 
265
 
    def __init__(self, sock, backing_transport, root_client_path='/'):
 
95
    def __init__(self, sock, backing_transport):
266
96
        """Constructor.
267
97
 
268
98
        :param sock: the socket the server will read from.  It will be put
269
99
            into blocking mode.
270
100
        """
271
 
        SmartServerStreamMedium.__init__(
272
 
            self, backing_transport, root_client_path=root_client_path)
 
101
        SmartServerStreamMedium.__init__(self, backing_transport)
 
102
        self.push_back = ''
273
103
        sock.setblocking(True)
274
104
        self.socket = sock
275
105
 
276
106
    def _serve_one_request_unguarded(self, protocol):
277
107
        while protocol.next_read_size():
278
 
            # We can safely try to read large chunks.  If there is less data
279
 
            # than _MAX_READ_SIZE ready, the socket wil just return a short
280
 
            # read immediately rather than block.
281
 
            bytes = self.read_bytes(_MAX_READ_SIZE)
282
 
            if bytes == '':
283
 
                self.finished = True
284
 
                return
285
 
            protocol.accept_bytes(bytes)
286
 
 
287
 
        self._push_back(protocol.unused_data)
288
 
 
289
 
    def _read_bytes(self, desired_count):
290
 
        return _read_bytes_from_socket(
291
 
            self.socket.recv, desired_count, self._report_activity)
292
 
 
 
108
            if self.push_back:
 
109
                protocol.accept_bytes(self.push_back)
 
110
                self.push_back = ''
 
111
            else:
 
112
                bytes = self.socket.recv(4096)
 
113
                if bytes == '':
 
114
                    self.finished = True
 
115
                    return
 
116
                protocol.accept_bytes(bytes)
 
117
        
 
118
        self.push_back = protocol.excess_buffer
 
119
    
293
120
    def terminate_due_to_error(self):
 
121
        """Called when an unhandled exception from the protocol occurs."""
294
122
        # TODO: This should log to a server log file, but no such thing
295
123
        # exists yet.  Andrew Bennetts 2006-09-29.
296
 
        osutils.until_no_eintr(self.socket.close)
 
124
        self.socket.close()
297
125
        self.finished = True
298
126
 
299
127
    def _write_out(self, bytes):
300
 
        tstart = osutils.timer_func()
301
 
        osutils.send_all(self.socket, bytes, self._report_activity)
302
 
        if 'hpss' in debug.debug_flags:
303
 
            thread_id = thread.get_ident()
304
 
            trace.mutter('%12s: [%s] %d bytes to the socket in %.3fs'
305
 
                         % ('wrote', thread_id, len(bytes),
306
 
                            osutils.timer_func() - tstart))
 
128
        self.socket.sendall(bytes)
307
129
 
308
130
 
309
131
class SmartServerPipeStreamMedium(SmartServerStreamMedium):
328
150
 
329
151
    def _serve_one_request_unguarded(self, protocol):
330
152
        while True:
331
 
            # We need to be careful not to read past the end of the current
332
 
            # request, or else the read from the pipe will block, so we use
333
 
            # protocol.next_read_size().
334
153
            bytes_to_read = protocol.next_read_size()
335
154
            if bytes_to_read == 0:
336
155
                # Finished serving this request.
337
 
                osutils.until_no_eintr(self._out.flush)
 
156
                self._out.flush()
338
157
                return
339
 
            bytes = self.read_bytes(bytes_to_read)
 
158
            bytes = self._in.read(bytes_to_read)
340
159
            if bytes == '':
341
160
                # Connection has been closed.
342
161
                self.finished = True
343
 
                osutils.until_no_eintr(self._out.flush)
 
162
                self._out.flush()
344
163
                return
345
164
            protocol.accept_bytes(bytes)
346
165
 
347
 
    def _read_bytes(self, desired_count):
348
 
        return osutils.until_no_eintr(self._in.read, desired_count)
349
 
 
350
166
    def terminate_due_to_error(self):
351
167
        # TODO: This should log to a server log file, but no such thing
352
168
        # exists yet.  Andrew Bennetts 2006-09-29.
353
 
        osutils.until_no_eintr(self._out.close)
 
169
        self._out.close()
354
170
        self.finished = True
355
171
 
356
172
    def _write_out(self, bytes):
357
 
        osutils.until_no_eintr(self._out.write, bytes)
 
173
        self._out.write(bytes)
358
174
 
359
175
 
360
176
class SmartClientMediumRequest(object):
370
186
    request.finished_reading()
371
187
 
372
188
    It is up to the individual SmartClientMedium whether multiple concurrent
373
 
    requests can exist. See SmartClientMedium.get_request to obtain instances
374
 
    of SmartClientMediumRequest, and the concrete Medium you are using for
 
189
    requests can exist. See SmartClientMedium.get_request to obtain instances 
 
190
    of SmartClientMediumRequest, and the concrete Medium you are using for 
375
191
    details on concurrency and pipelining.
376
192
    """
377
193
 
386
202
    def accept_bytes(self, bytes):
387
203
        """Accept bytes for inclusion in this request.
388
204
 
389
 
        This method may not be called after finished_writing() has been
 
205
        This method may not be be called after finished_writing() has been
390
206
        called.  It depends upon the Medium whether or not the bytes will be
391
207
        immediately transmitted. Message based Mediums will tend to buffer the
392
208
        bytes until finished_writing() is called.
423
239
    def _finished_reading(self):
424
240
        """Helper for finished_reading.
425
241
 
426
 
        finished_reading checks the state of the request to determine if
 
242
        finished_reading checks the state of the request to determine if 
427
243
        finished_reading is allowed, and if it is hands off to _finished_reading
428
244
        to perform the action.
429
245
        """
443
259
    def _finished_writing(self):
444
260
        """Helper for finished_writing.
445
261
 
446
 
        finished_writing checks the state of the request to determine if
 
262
        finished_writing checks the state of the request to determine if 
447
263
        finished_writing is allowed, and if it is hands off to _finished_writing
448
264
        to perform the action.
449
265
        """
454
270
 
455
271
        This method will block and wait for count bytes to be read. It may not
456
272
        be invoked until finished_writing() has been called - this is to ensure
457
 
        a message-based approach to requests, for compatibility with message
 
273
        a message-based approach to requests, for compatability with message
458
274
        based mediums like HTTP.
459
275
        """
460
276
        if self._state == "writing":
464
280
        return self._read_bytes(count)
465
281
 
466
282
    def _read_bytes(self, count):
467
 
        """Helper for SmartClientMediumRequest.read_bytes.
 
283
        """Helper for read_bytes.
468
284
 
469
285
        read_bytes checks the state of the request to determing if bytes
470
286
        should be read. After that it hands off to _read_bytes to do the
471
287
        actual read.
472
 
 
473
 
        By default this forwards to self._medium.read_bytes because we are
474
 
        operating on the medium's stream.
475
 
        """
476
 
        return self._medium.read_bytes(count)
477
 
 
478
 
    def read_line(self):
479
 
        line = self._read_line()
480
 
        if not line.endswith('\n'):
481
 
            # end of file encountered reading from server
482
 
            raise errors.ConnectionReset(
483
 
                "Unexpected end of message. Please check connectivity "
484
 
                "and permissions, and report a bug if problems persist.")
485
 
        return line
486
 
 
487
 
    def _read_line(self):
488
 
        """Helper for SmartClientMediumRequest.read_line.
489
 
 
490
 
        By default this forwards to self._medium._get_line because we are
491
 
        operating on the medium's stream.
492
 
        """
493
 
        return self._medium._get_line()
494
 
 
495
 
 
496
 
class _DebugCounter(object):
497
 
    """An object that counts the HPSS calls made to each client medium.
498
 
 
499
 
    When a medium is garbage-collected, or failing that when atexit functions
500
 
    are run, the total number of calls made on that medium are reported via
501
 
    trace.note.
502
 
    """
503
 
 
504
 
    def __init__(self):
505
 
        self.counts = weakref.WeakKeyDictionary()
506
 
        client._SmartClient.hooks.install_named_hook(
507
 
            'call', self.increment_call_count, 'hpss call counter')
508
 
        atexit.register(self.flush_all)
509
 
 
510
 
    def track(self, medium):
511
 
        """Start tracking calls made to a medium.
512
 
 
513
 
        This only keeps a weakref to the medium, so shouldn't affect the
514
 
        medium's lifetime.
515
 
        """
516
 
        medium_repr = repr(medium)
517
 
        # Add this medium to the WeakKeyDictionary
518
 
        self.counts[medium] = dict(count=0, vfs_count=0,
519
 
                                   medium_repr=medium_repr)
520
 
        # Weakref callbacks are fired in reverse order of their association
521
 
        # with the referenced object.  So we add a weakref *after* adding to
522
 
        # the WeakKeyDict so that we can report the value from it before the
523
 
        # entry is removed by the WeakKeyDict's own callback.
524
 
        ref = weakref.ref(medium, self.done)
525
 
 
526
 
    def increment_call_count(self, params):
527
 
        # Increment the count in the WeakKeyDictionary
528
 
        value = self.counts[params.medium]
529
 
        value['count'] += 1
530
 
        try:
531
 
            request_method = request.request_handlers.get(params.method)
532
 
        except KeyError:
533
 
            # A method we don't know about doesn't count as a VFS method.
534
 
            return
535
 
        if issubclass(request_method, vfs.VfsRequest):
536
 
            value['vfs_count'] += 1
537
 
 
538
 
    def done(self, ref):
539
 
        value = self.counts[ref]
540
 
        count, vfs_count, medium_repr = (
541
 
            value['count'], value['vfs_count'], value['medium_repr'])
542
 
        # In case this callback is invoked for the same ref twice (by the
543
 
        # weakref callback and by the atexit function), set the call count back
544
 
        # to 0 so this item won't be reported twice.
545
 
        value['count'] = 0
546
 
        value['vfs_count'] = 0
547
 
        if count != 0:
548
 
            trace.note('HPSS calls: %d (%d vfs) %s',
549
 
                       count, vfs_count, medium_repr)
550
 
 
551
 
    def flush_all(self):
552
 
        for ref in list(self.counts.keys()):
553
 
            self.done(ref)
554
 
 
555
 
_debug_counter = None
556
 
 
557
 
 
558
 
class SmartClientMedium(SmartMedium):
 
288
        """
 
289
        raise NotImplementedError(self._read_bytes)
 
290
 
 
291
 
 
292
class SmartClientMedium(object):
559
293
    """Smart client is a medium for sending smart protocol requests over."""
560
294
 
561
 
    def __init__(self, base):
562
 
        super(SmartClientMedium, self).__init__()
563
 
        self.base = base
564
 
        self._protocol_version_error = None
565
 
        self._protocol_version = None
566
 
        self._done_hello = False
567
 
        # Be optimistic: we assume the remote end can accept new remote
568
 
        # requests until we get an error saying otherwise.
569
 
        # _remote_version_is_before tracks the bzr version the remote side
570
 
        # can be based on what we've seen so far.
571
 
        self._remote_version_is_before = None
572
 
        # Install debug hook function if debug flag is set.
573
 
        if 'hpss' in debug.debug_flags:
574
 
            global _debug_counter
575
 
            if _debug_counter is None:
576
 
                _debug_counter = _DebugCounter()
577
 
            _debug_counter.track(self)
578
 
 
579
 
    def _is_remote_before(self, version_tuple):
580
 
        """Is it possible the remote side supports RPCs for a given version?
581
 
 
582
 
        Typical use::
583
 
 
584
 
            needed_version = (1, 2)
585
 
            if medium._is_remote_before(needed_version):
586
 
                fallback_to_pre_1_2_rpc()
587
 
            else:
588
 
                try:
589
 
                    do_1_2_rpc()
590
 
                except UnknownSmartMethod:
591
 
                    medium._remember_remote_is_before(needed_version)
592
 
                    fallback_to_pre_1_2_rpc()
593
 
 
594
 
        :seealso: _remember_remote_is_before
595
 
        """
596
 
        if self._remote_version_is_before is None:
597
 
            # So far, the remote side seems to support everything
598
 
            return False
599
 
        return version_tuple >= self._remote_version_is_before
600
 
 
601
 
    def _remember_remote_is_before(self, version_tuple):
602
 
        """Tell this medium that the remote side is older the given version.
603
 
 
604
 
        :seealso: _is_remote_before
605
 
        """
606
 
        if (self._remote_version_is_before is not None and
607
 
            version_tuple > self._remote_version_is_before):
608
 
            # We have been told that the remote side is older than some version
609
 
            # which is newer than a previously supplied older-than version.
610
 
            # This indicates that some smart verb call is not guarded
611
 
            # appropriately (it should simply not have been tried).
612
 
            raise AssertionError(
613
 
                "_remember_remote_is_before(%r) called, but "
614
 
                "_remember_remote_is_before(%r) was called previously."
615
 
                % (version_tuple, self._remote_version_is_before))
616
 
        self._remote_version_is_before = version_tuple
617
 
 
618
 
    def protocol_version(self):
619
 
        """Find out if 'hello' smart request works."""
620
 
        if self._protocol_version_error is not None:
621
 
            raise self._protocol_version_error
622
 
        if not self._done_hello:
623
 
            try:
624
 
                medium_request = self.get_request()
625
 
                # Send a 'hello' request in protocol version one, for maximum
626
 
                # backwards compatibility.
627
 
                client_protocol = protocol.SmartClientRequestProtocolOne(medium_request)
628
 
                client_protocol.query_version()
629
 
                self._done_hello = True
630
 
            except errors.SmartProtocolError, e:
631
 
                # Cache the error, just like we would cache a successful
632
 
                # result.
633
 
                self._protocol_version_error = e
634
 
                raise
635
 
        return '2'
636
 
 
637
 
    def should_probe(self):
638
 
        """Should RemoteBzrDirFormat.probe_transport send a smart request on
639
 
        this medium?
640
 
 
641
 
        Some transports are unambiguously smart-only; there's no need to check
642
 
        if the transport is able to carry smart requests, because that's all
643
 
        it is for.  In those cases, this method should return False.
644
 
 
645
 
        But some HTTP transports can sometimes fail to carry smart requests,
646
 
        but still be usuable for accessing remote bzrdirs via plain file
647
 
        accesses.  So for those transports, their media should return True here
648
 
        so that RemoteBzrDirFormat can determine if it is appropriate for that
649
 
        transport.
650
 
        """
651
 
        return False
652
 
 
653
295
    def disconnect(self):
654
296
        """If this medium maintains a persistent connection, close it.
655
 
 
 
297
        
656
298
        The default implementation does nothing.
657
299
        """
658
 
 
659
 
    def remote_path_from_transport(self, transport):
660
 
        """Convert transport into a path suitable for using in a request.
661
 
 
662
 
        Note that the resulting remote path doesn't encode the host name or
663
 
        anything but path, so it is only safe to use it in requests sent over
664
 
        the medium from the matching transport.
665
 
        """
666
 
        medium_base = urlutils.join(self.base, '/')
667
 
        rel_url = urlutils.relative_url(medium_base, transport.base)
668
 
        return urllib.unquote(rel_url)
669
 
 
 
300
        
670
301
 
671
302
class SmartClientStreamMedium(SmartClientMedium):
672
303
    """Stream based medium common class.
677
308
    receive bytes.
678
309
    """
679
310
 
680
 
    def __init__(self, base):
681
 
        SmartClientMedium.__init__(self, base)
 
311
    def __init__(self):
682
312
        self._current_request = None
683
313
 
684
314
    def accept_bytes(self, bytes):
692
322
 
693
323
    def _flush(self):
694
324
        """Flush the output stream.
695
 
 
 
325
        
696
326
        This method is used by the SmartClientStreamMediumRequest to ensure that
697
327
        all data for a request is sent, to avoid long timeouts or deadlocks.
698
328
        """
706
336
        """
707
337
        return SmartClientStreamMediumRequest(self)
708
338
 
 
339
    def read_bytes(self, count):
 
340
        return self._read_bytes(count)
 
341
 
709
342
 
710
343
class SmartSimplePipesClientMedium(SmartClientStreamMedium):
711
344
    """A client medium using simple pipes.
712
 
 
 
345
    
713
346
    This client does not manage the pipes: it assumes they will always be open.
714
347
    """
715
348
 
716
 
    def __init__(self, readable_pipe, writeable_pipe, base):
717
 
        SmartClientStreamMedium.__init__(self, base)
 
349
    def __init__(self, readable_pipe, writeable_pipe):
 
350
        SmartClientStreamMedium.__init__(self)
718
351
        self._readable_pipe = readable_pipe
719
352
        self._writeable_pipe = writeable_pipe
720
353
 
721
354
    def _accept_bytes(self, bytes):
722
355
        """See SmartClientStreamMedium.accept_bytes."""
723
 
        osutils.until_no_eintr(self._writeable_pipe.write, bytes)
724
 
        self._report_activity(len(bytes), 'write')
 
356
        self._writeable_pipe.write(bytes)
725
357
 
726
358
    def _flush(self):
727
359
        """See SmartClientStreamMedium._flush()."""
728
 
        osutils.until_no_eintr(self._writeable_pipe.flush)
 
360
        self._writeable_pipe.flush()
729
361
 
730
362
    def _read_bytes(self, count):
731
363
        """See SmartClientStreamMedium._read_bytes."""
732
 
        bytes = osutils.until_no_eintr(self._readable_pipe.read, count)
733
 
        self._report_activity(len(bytes), 'read')
734
 
        return bytes
 
364
        return self._readable_pipe.read(count)
735
365
 
736
366
 
737
367
class SmartSSHClientMedium(SmartClientStreamMedium):
738
368
    """A client medium using SSH."""
739
 
 
 
369
    
740
370
    def __init__(self, host, port=None, username=None, password=None,
741
 
            base=None, vendor=None, bzr_remote_path=None):
 
371
            vendor=None):
742
372
        """Creates a client that will connect on the first use.
743
 
 
 
373
        
744
374
        :param vendor: An optional override for the ssh vendor to use. See
745
375
            bzrlib.transport.ssh for details on ssh vendors.
746
376
        """
 
377
        SmartClientStreamMedium.__init__(self)
747
378
        self._connected = False
748
379
        self._host = host
749
380
        self._password = password
750
381
        self._port = port
751
382
        self._username = username
752
 
        # for the benefit of progress making a short description of this
753
 
        # transport
754
 
        self._scheme = 'bzr+ssh'
755
 
        # SmartClientStreamMedium stores the repr of this object in its
756
 
        # _DebugCounter so we have to store all the values used in our repr
757
 
        # method before calling the super init.
758
 
        SmartClientStreamMedium.__init__(self, base)
759
383
        self._read_from = None
760
384
        self._ssh_connection = None
761
385
        self._vendor = vendor
762
386
        self._write_to = None
763
 
        self._bzr_remote_path = bzr_remote_path
764
 
 
765
 
    def __repr__(self):
766
 
        if self._port is None:
767
 
            maybe_port = ''
768
 
        else:
769
 
            maybe_port = ':%s' % self._port
770
 
        return "%s(%s://%s@%s%s/)" % (
771
 
            self.__class__.__name__,
772
 
            self._scheme,
773
 
            self._username,
774
 
            self._host,
775
 
            maybe_port)
776
387
 
777
388
    def _accept_bytes(self, bytes):
778
389
        """See SmartClientStreamMedium.accept_bytes."""
779
390
        self._ensure_connection()
780
 
        osutils.until_no_eintr(self._write_to.write, bytes)
781
 
        self._report_activity(len(bytes), 'write')
 
391
        self._write_to.write(bytes)
782
392
 
783
393
    def disconnect(self):
784
394
        """See SmartClientMedium.disconnect()."""
785
395
        if not self._connected:
786
396
            return
787
 
        osutils.until_no_eintr(self._read_from.close)
788
 
        osutils.until_no_eintr(self._write_to.close)
 
397
        self._read_from.close()
 
398
        self._write_to.close()
789
399
        self._ssh_connection.close()
790
400
        self._connected = False
791
401
 
793
403
        """Connect this medium if not already connected."""
794
404
        if self._connected:
795
405
            return
 
406
        executable = os.environ.get('BZR_REMOTE_PATH', 'bzr')
796
407
        if self._vendor is None:
797
408
            vendor = ssh._get_ssh_vendor()
798
409
        else:
799
410
            vendor = self._vendor
800
411
        self._ssh_connection = vendor.connect_ssh(self._username,
801
412
                self._password, self._host, self._port,
802
 
                command=[self._bzr_remote_path, 'serve', '--inet',
803
 
                         '--directory=/', '--allow-writes'])
 
413
                command=[executable, 'serve', '--inet', '--directory=/',
 
414
                         '--allow-writes'])
804
415
        self._read_from, self._write_to = \
805
416
            self._ssh_connection.get_filelike_channels()
806
417
        self._connected = True
813
424
        """See SmartClientStreamMedium.read_bytes."""
814
425
        if not self._connected:
815
426
            raise errors.MediumNotConnected(self)
816
 
        bytes_to_read = min(count, _MAX_READ_SIZE)
817
 
        bytes = osutils.until_no_eintr(self._read_from.read, bytes_to_read)
818
 
        self._report_activity(len(bytes), 'read')
819
 
        return bytes
820
 
 
821
 
 
822
 
# Port 4155 is the default port for bzr://, registered with IANA.
823
 
BZR_DEFAULT_INTERFACE = None
824
 
BZR_DEFAULT_PORT = 4155
 
427
        return self._read_from.read(count)
825
428
 
826
429
 
827
430
class SmartTCPClientMedium(SmartClientStreamMedium):
828
431
    """A client medium using TCP."""
829
 
 
830
 
    def __init__(self, host, port, base):
 
432
    
 
433
    def __init__(self, host, port):
831
434
        """Creates a client that will connect on the first use."""
832
 
        SmartClientStreamMedium.__init__(self, base)
 
435
        SmartClientStreamMedium.__init__(self)
833
436
        self._connected = False
834
437
        self._host = host
835
438
        self._port = port
838
441
    def _accept_bytes(self, bytes):
839
442
        """See SmartClientMedium.accept_bytes."""
840
443
        self._ensure_connection()
841
 
        osutils.send_all(self._socket, bytes, self._report_activity)
 
444
        self._socket.sendall(bytes)
842
445
 
843
446
    def disconnect(self):
844
447
        """See SmartClientMedium.disconnect()."""
845
448
        if not self._connected:
846
449
            return
847
 
        osutils.until_no_eintr(self._socket.close)
 
450
        self._socket.close()
848
451
        self._socket = None
849
452
        self._connected = False
850
453
 
852
455
        """Connect this medium if not already connected."""
853
456
        if self._connected:
854
457
            return
855
 
        if self._port is None:
856
 
            port = BZR_DEFAULT_PORT
857
 
        else:
858
 
            port = int(self._port)
859
 
        try:
860
 
            sockaddrs = socket.getaddrinfo(self._host, port, socket.AF_UNSPEC,
861
 
                socket.SOCK_STREAM, 0, 0)
862
 
        except socket.gaierror, (err_num, err_msg):
863
 
            raise errors.ConnectionError("failed to lookup %s:%d: %s" %
864
 
                    (self._host, port, err_msg))
865
 
        # Initialize err in case there are no addresses returned:
866
 
        err = socket.error("no address found for %s" % self._host)
867
 
        for (family, socktype, proto, canonname, sockaddr) in sockaddrs:
868
 
            try:
869
 
                self._socket = socket.socket(family, socktype, proto)
870
 
                self._socket.setsockopt(socket.IPPROTO_TCP,
871
 
                                        socket.TCP_NODELAY, 1)
872
 
                self._socket.connect(sockaddr)
873
 
            except socket.error, err:
874
 
                if self._socket is not None:
875
 
                    self._socket.close()
876
 
                self._socket = None
877
 
                continue
878
 
            break
879
 
        if self._socket is None:
880
 
            # socket errors either have a (string) or (errno, string) as their
881
 
            # args.
882
 
            if type(err.args) is str:
883
 
                err_msg = err.args
884
 
            else:
885
 
                err_msg = err.args[1]
 
458
        self._socket = socket.socket()
 
459
        self._socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
 
460
        result = self._socket.connect_ex((self._host, int(self._port)))
 
461
        if result:
886
462
            raise errors.ConnectionError("failed to connect to %s:%d: %s" %
887
 
                    (self._host, port, err_msg))
 
463
                    (self._host, self._port, os.strerror(result)))
888
464
        self._connected = True
889
465
 
890
466
    def _flush(self):
891
467
        """See SmartClientStreamMedium._flush().
892
 
 
893
 
        For TCP we do no flushing. We may want to turn off TCP_NODELAY and
 
468
        
 
469
        For TCP we do no flushing. We may want to turn off TCP_NODELAY and 
894
470
        add a means to do a flush, but that can be done in the future.
895
471
        """
896
472
 
898
474
        """See SmartClientMedium.read_bytes."""
899
475
        if not self._connected:
900
476
            raise errors.MediumNotConnected(self)
901
 
        return _read_bytes_from_socket(
902
 
            self._socket.recv, count, self._report_activity)
 
477
        return self._socket.recv(count)
903
478
 
904
479
 
905
480
class SmartClientStreamMediumRequest(SmartClientMediumRequest):
918
493
 
919
494
    def _accept_bytes(self, bytes):
920
495
        """See SmartClientMediumRequest._accept_bytes.
921
 
 
 
496
        
922
497
        This forwards to self._medium._accept_bytes because we are operating
923
498
        on the mediums stream.
924
499
        """
927
502
    def _finished_reading(self):
928
503
        """See SmartClientMediumRequest._finished_reading.
929
504
 
930
 
        This clears the _current_request on self._medium to allow a new
 
505
        This clears the _current_request on self._medium to allow a new 
931
506
        request to be created.
932
507
        """
933
 
        if self._medium._current_request is not self:
934
 
            raise AssertionError()
 
508
        assert self._medium._current_request is self
935
509
        self._medium._current_request = None
936
 
 
 
510
        
937
511
    def _finished_writing(self):
938
512
        """See SmartClientMediumRequest._finished_writing.
939
513
 
941
515
        """
942
516
        self._medium._flush()
943
517
 
 
518
    def _read_bytes(self, count):
 
519
        """See SmartClientMediumRequest._read_bytes.
 
520
        
 
521
        This forwards to self._medium._read_bytes because we are operating
 
522
        on the mediums stream.
 
523
        """
 
524
        return self._medium._read_bytes(count)
944
525
 
945
 
def _read_bytes_from_socket(sock, desired_count, report_activity):
946
 
    # We ignore the desired_count because on sockets it's more efficient to
947
 
    # read large chunks (of _MAX_READ_SIZE bytes) at a time.
948
 
    try:
949
 
        bytes = osutils.until_no_eintr(sock, _MAX_READ_SIZE)
950
 
    except socket.error, e:
951
 
        if len(e.args) and e.args[0] in (errno.ECONNRESET, 10054):
952
 
            # The connection was closed by the other side.  Callers expect an
953
 
            # empty string to signal end-of-stream.
954
 
            bytes = ''
955
 
        else:
956
 
            raise
957
 
    else:
958
 
        report_activity(len(bytes), 'read')
959
 
    return bytes
960
526