/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

  • Committer: Andrew Bennetts
  • Date: 2009-07-15 06:39:07 UTC
  • mto: (4476.3.44 inventory-delta)
  • mto: This revision was merged to the branch mainline in revision 4608.
  • Revision ID: andrew.bennetts@canonical.com-20090715063907-rw44os6ox1253nm8
Trivial improvement to test coverage in test_xml.

Show diffs side-by-side

added added

removed removed

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