/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: 2010-03-05 07:27:58 UTC
  • mto: This revision was merged to the branch mainline in revision 5117.
  • Revision ID: andrew.bennetts@canonical.com-20100305072758-9il5cvpa4gjo8tba
Try a bit harder to stop a SmartTCPServer sooner when _should_terminate has been set.

Show diffs side-by-side

added added

removed removed

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