/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

Switch Win32ReadDirFeature, which was probing for the wrong module anyway... :)

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