~ubuntu-branches/ubuntu/karmic/bzr/karmic-proposed

« back to all changes in this revision

Viewing changes to bzrlib/smart/medium.py

  • Committer: Bazaar Package Importer
  • Author(s): Jelmer Vernooij
  • Date: 2008-08-25 19:06:49 UTC
  • mfrom: (1.1.44 upstream)
  • Revision ID: james.westby@ubuntu.com-20080825190649-pq87jonr4uvs7s0y
Tags: 1.6-1
New upstream release.

Show diffs side-by-side

added added

removed removed

Lines of Context:
27
27
import os
28
28
import socket
29
29
import sys
 
30
import urllib
30
31
 
 
32
from bzrlib.lazy_import import lazy_import
 
33
lazy_import(globals(), """
31
34
from bzrlib import (
32
35
    errors,
33
36
    osutils,
34
37
    symbol_versioning,
35
 
    )
36
 
from bzrlib.smart.protocol import (
37
 
    REQUEST_VERSION_TWO,
38
 
    SmartClientRequestProtocolOne,
39
 
    SmartServerRequestProtocolOne,
40
 
    SmartServerRequestProtocolTwo,
41
 
    )
 
38
    urlutils,
 
39
    )
 
40
from bzrlib.smart import protocol
42
41
from bzrlib.transport import ssh
43
 
 
44
 
 
45
 
class SmartServerStreamMedium(object):
 
42
""")
 
43
 
 
44
 
 
45
# We must not read any more than 64k at a time so we don't risk "no buffer
 
46
# space available" errors on some platforms.  Windows in particular is likely
 
47
# to give error 10053 or 10055 if we read more than 64k from a socket.
 
48
_MAX_READ_SIZE = 64 * 1024
 
49
 
 
50
 
 
51
def _get_protocol_factory_for_bytes(bytes):
 
52
    """Determine the right protocol factory for 'bytes'.
 
53
 
 
54
    This will return an appropriate protocol factory depending on the version
 
55
    of the protocol being used, as determined by inspecting the given bytes.
 
56
    The bytes should have at least one newline byte (i.e. be a whole line),
 
57
    otherwise it's possible that a request will be incorrectly identified as
 
58
    version 1.
 
59
 
 
60
    Typical use would be::
 
61
 
 
62
         factory, unused_bytes = _get_protocol_factory_for_bytes(bytes)
 
63
         server_protocol = factory(transport, write_func, root_client_path)
 
64
         server_protocol.accept_bytes(unused_bytes)
 
65
 
 
66
    :param bytes: a str of bytes of the start of the request.
 
67
    :returns: 2-tuple of (protocol_factory, unused_bytes).  protocol_factory is
 
68
        a callable that takes three args: transport, write_func,
 
69
        root_client_path.  unused_bytes are any bytes that were not part of a
 
70
        protocol version marker.
 
71
    """
 
72
    if bytes.startswith(protocol.MESSAGE_VERSION_THREE):
 
73
        protocol_factory = protocol.build_server_protocol_three
 
74
        bytes = bytes[len(protocol.MESSAGE_VERSION_THREE):]
 
75
    elif bytes.startswith(protocol.REQUEST_VERSION_TWO):
 
76
        protocol_factory = protocol.SmartServerRequestProtocolTwo
 
77
        bytes = bytes[len(protocol.REQUEST_VERSION_TWO):]
 
78
    else:
 
79
        protocol_factory = protocol.SmartServerRequestProtocolOne
 
80
    return protocol_factory, bytes
 
81
 
 
82
 
 
83
def _get_line(read_bytes_func):
 
84
    """Read bytes using read_bytes_func until a newline byte.
 
85
    
 
86
    This isn't particularly efficient, so should only be used when the
 
87
    expected size of the line is quite short.
 
88
    
 
89
    :returns: a tuple of two strs: (line, excess)
 
90
    """
 
91
    newline_pos = -1
 
92
    bytes = ''
 
93
    while newline_pos == -1:
 
94
        new_bytes = read_bytes_func(1)
 
95
        bytes += new_bytes
 
96
        if new_bytes == '':
 
97
            # Ran out of bytes before receiving a complete line.
 
98
            return bytes, ''
 
99
        newline_pos = bytes.find('\n')
 
100
    line = bytes[:newline_pos+1]
 
101
    excess = bytes[newline_pos+1:]
 
102
    return line, excess
 
103
 
 
104
 
 
105
class SmartMedium(object):
 
106
    """Base class for smart protocol media, both client- and server-side."""
 
107
 
 
108
    def __init__(self):
 
109
        self._push_back_buffer = None
 
110
        
 
111
    def _push_back(self, bytes):
 
112
        """Return unused bytes to the medium, because they belong to the next
 
113
        request(s).
 
114
 
 
115
        This sets the _push_back_buffer to the given bytes.
 
116
        """
 
117
        if self._push_back_buffer is not None:
 
118
            raise AssertionError(
 
119
                "_push_back called when self._push_back_buffer is %r"
 
120
                % (self._push_back_buffer,))
 
121
        if bytes == '':
 
122
            return
 
123
        self._push_back_buffer = bytes
 
124
 
 
125
    def _get_push_back_buffer(self):
 
126
        if self._push_back_buffer == '':
 
127
            raise AssertionError(
 
128
                '%s._push_back_buffer should never be the empty string, '
 
129
                'which can be confused with EOF' % (self,))
 
130
        bytes = self._push_back_buffer
 
131
        self._push_back_buffer = None
 
132
        return bytes
 
133
 
 
134
    def read_bytes(self, desired_count):
 
135
        """Read some bytes from this medium.
 
136
 
 
137
        :returns: some bytes, possibly more or less than the number requested
 
138
            in 'desired_count' depending on the medium.
 
139
        """
 
140
        if self._push_back_buffer is not None:
 
141
            return self._get_push_back_buffer()
 
142
        bytes_to_read = min(desired_count, _MAX_READ_SIZE)
 
143
        return self._read_bytes(bytes_to_read)
 
144
 
 
145
    def _read_bytes(self, count):
 
146
        raise NotImplementedError(self._read_bytes)
 
147
 
 
148
    def _get_line(self):
 
149
        """Read bytes from this request's response until a newline byte.
 
150
        
 
151
        This isn't particularly efficient, so should only be used when the
 
152
        expected size of the line is quite short.
 
153
 
 
154
        :returns: a string of bytes ending in a newline (byte 0x0A).
 
155
        """
 
156
        line, excess = _get_line(self.read_bytes)
 
157
        self._push_back(excess)
 
158
        return line
 
159
 
 
160
 
 
161
class SmartServerStreamMedium(SmartMedium):
46
162
    """Handles smart commands coming over a stream.
47
163
 
48
164
    The stream may be a pipe connected to sshd, or a tcp socket, or an
69
185
        self.backing_transport = backing_transport
70
186
        self.root_client_path = root_client_path
71
187
        self.finished = False
72
 
        self._push_back_buffer = None
73
 
 
74
 
    def _push_back(self, bytes):
75
 
        """Return unused bytes to the medium, because they belong to the next
76
 
        request(s).
77
 
 
78
 
        This sets the _push_back_buffer to the given bytes.
79
 
        """
80
 
        if self._push_back_buffer is not None:
81
 
            raise AssertionError(
82
 
                "_push_back called when self._push_back_buffer is %r"
83
 
                % (self._push_back_buffer,))
84
 
        if bytes == '':
85
 
            return
86
 
        self._push_back_buffer = bytes
87
 
 
88
 
    def _get_push_back_buffer(self):
89
 
        if self._push_back_buffer == '':
90
 
            raise AssertionError(
91
 
                '%s._push_back_buffer should never be the empty string, '
92
 
                'which can be confused with EOF' % (self,))
93
 
        bytes = self._push_back_buffer
94
 
        self._push_back_buffer = None
95
 
        return bytes
 
188
        SmartMedium.__init__(self)
96
189
 
97
190
    def serve(self):
98
191
        """Serve requests until the client disconnects."""
116
209
 
117
210
        :returns: a SmartServerRequestProtocol.
118
211
        """
119
 
        # Identify the protocol version.
120
212
        bytes = self._get_line()
121
 
        if bytes.startswith(REQUEST_VERSION_TWO):
122
 
            protocol_class = SmartServerRequestProtocolTwo
123
 
            bytes = bytes[len(REQUEST_VERSION_TWO):]
124
 
        else:
125
 
            protocol_class = SmartServerRequestProtocolOne
126
 
        protocol = protocol_class(
 
213
        protocol_factory, unused_bytes = _get_protocol_factory_for_bytes(bytes)
 
214
        protocol = protocol_factory(
127
215
            self.backing_transport, self._write_out, self.root_client_path)
128
 
        protocol.accept_bytes(bytes)
 
216
        protocol.accept_bytes(unused_bytes)
129
217
        return protocol
130
218
 
131
219
    def _serve_one_request(self, protocol):
144
232
        """Called when an unhandled exception from the protocol occurs."""
145
233
        raise NotImplementedError(self.terminate_due_to_error)
146
234
 
147
 
    def _get_bytes(self, desired_count):
 
235
    def _read_bytes(self, desired_count):
148
236
        """Get some bytes from the medium.
149
237
 
150
238
        :param desired_count: number of bytes we want to read.
151
239
        """
152
 
        raise NotImplementedError(self._get_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
 
        newline_pos = -1
163
 
        bytes = ''
164
 
        while newline_pos == -1:
165
 
            new_bytes = self._get_bytes(1)
166
 
            bytes += new_bytes
167
 
            if new_bytes == '':
168
 
                # Ran out of bytes before receiving a complete line.
169
 
                return bytes
170
 
            newline_pos = bytes.find('\n')
171
 
        line = bytes[:newline_pos+1]
172
 
        self._push_back(bytes[newline_pos+1:])
173
 
        return line
174
 
 
 
240
        raise NotImplementedError(self._read_bytes)
 
241
 
175
242
 
176
243
class SmartServerSocketStreamMedium(SmartServerStreamMedium):
177
244
 
188
255
 
189
256
    def _serve_one_request_unguarded(self, protocol):
190
257
        while protocol.next_read_size():
191
 
            bytes = self._get_bytes(4096)
 
258
            # We can safely try to read large chunks.  If there is less data
 
259
            # than _MAX_READ_SIZE ready, the socket wil just return a short
 
260
            # read immediately rather than block.
 
261
            bytes = self.read_bytes(_MAX_READ_SIZE)
192
262
            if bytes == '':
193
263
                self.finished = True
194
264
                return
195
265
            protocol.accept_bytes(bytes)
196
266
        
197
 
        self._push_back(protocol.excess_buffer)
 
267
        self._push_back(protocol.unused_data)
198
268
 
199
 
    def _get_bytes(self, desired_count):
200
 
        if self._push_back_buffer is not None:
201
 
            return self._get_push_back_buffer()
 
269
    def _read_bytes(self, desired_count):
202
270
        # We ignore the desired_count because on sockets it's more efficient to
203
 
        # read 4k at a time.
204
 
        return self.socket.recv(4096)
205
 
    
 
271
        # read large chunks (of _MAX_READ_SIZE bytes) at a time.
 
272
        return self.socket.recv(_MAX_READ_SIZE)
 
273
 
206
274
    def terminate_due_to_error(self):
207
 
        """Called when an unhandled exception from the protocol occurs."""
208
275
        # TODO: This should log to a server log file, but no such thing
209
276
        # exists yet.  Andrew Bennetts 2006-09-29.
210
277
        self.socket.close()
236
303
 
237
304
    def _serve_one_request_unguarded(self, protocol):
238
305
        while True:
 
306
            # We need to be careful not to read past the end of the current
 
307
            # request, or else the read from the pipe will block, so we use
 
308
            # protocol.next_read_size().
239
309
            bytes_to_read = protocol.next_read_size()
240
310
            if bytes_to_read == 0:
241
311
                # Finished serving this request.
242
312
                self._out.flush()
243
313
                return
244
 
            bytes = self._get_bytes(bytes_to_read)
 
314
            bytes = self.read_bytes(bytes_to_read)
245
315
            if bytes == '':
246
316
                # Connection has been closed.
247
317
                self.finished = True
249
319
                return
250
320
            protocol.accept_bytes(bytes)
251
321
 
252
 
    def _get_bytes(self, desired_count):
253
 
        if self._push_back_buffer is not None:
254
 
            return self._get_push_back_buffer()
 
322
    def _read_bytes(self, desired_count):
255
323
        return self._in.read(desired_count)
256
324
 
257
325
    def terminate_due_to_error(self):
371
439
        return self._read_bytes(count)
372
440
 
373
441
    def _read_bytes(self, count):
374
 
        """Helper for read_bytes.
 
442
        """Helper for SmartClientMediumRequest.read_bytes.
375
443
 
376
444
        read_bytes checks the state of the request to determing if bytes
377
445
        should be read. After that it hands off to _read_bytes to do the
378
446
        actual read.
 
447
        
 
448
        By default this forwards to self._medium.read_bytes because we are
 
449
        operating on the medium's stream.
379
450
        """
380
 
        raise NotImplementedError(self._read_bytes)
 
451
        return self._medium.read_bytes(count)
381
452
 
382
453
    def read_line(self):
383
 
        """Read bytes from this request's response until a newline byte.
 
454
        line = self._read_line()
 
455
        if not line.endswith('\n'):
 
456
            # end of file encountered reading from server
 
457
            raise errors.ConnectionReset(
 
458
                "please check connectivity and permissions",
 
459
                "(and try -Dhpss if further diagnosis is required)")
 
460
        return line
 
461
 
 
462
    def _read_line(self):
 
463
        """Helper for SmartClientMediumRequest.read_line.
384
464
        
385
 
        This isn't particularly efficient, so should only be used when the
386
 
        expected size of the line is quite short.
387
 
 
388
 
        :returns: a string of bytes ending in a newline (byte 0x0A).
 
465
        By default this forwards to self._medium._get_line because we are
 
466
        operating on the medium's stream.
389
467
        """
390
 
        # XXX: this duplicates SmartClientRequestProtocolOne._recv_tuple
391
 
        line = ''
392
 
        while not line or line[-1] != '\n':
393
 
            new_char = self.read_bytes(1)
394
 
            line += new_char
395
 
            if new_char == '':
396
 
                # end of file encountered reading from server
397
 
                raise errors.ConnectionReset(
398
 
                    "please check connectivity and permissions",
399
 
                    "(and try -Dhpss if further diagnosis is required)")
400
 
        return line
401
 
 
402
 
 
403
 
class SmartClientMedium(object):
 
468
        return self._medium._get_line()
 
469
 
 
470
 
 
471
class SmartClientMedium(SmartMedium):
404
472
    """Smart client is a medium for sending smart protocol requests over."""
405
473
 
406
 
    def __init__(self):
 
474
    def __init__(self, base):
407
475
        super(SmartClientMedium, self).__init__()
 
476
        self.base = base
408
477
        self._protocol_version_error = None
409
478
        self._protocol_version = None
 
479
        self._done_hello = False
 
480
        # Be optimistic: we assume the remote end can accept new remote
 
481
        # requests until we get an error saying otherwise.
 
482
        # _remote_version_is_before tracks the bzr version the remote side
 
483
        # can be based on what we've seen so far.
 
484
        self._remote_version_is_before = None
 
485
 
 
486
    def _is_remote_before(self, version_tuple):
 
487
        """Is it possible the remote side supports RPCs for a given version?
 
488
 
 
489
        Typical use::
 
490
 
 
491
            needed_version = (1, 2)
 
492
            if medium._is_remote_before(needed_version):
 
493
                fallback_to_pre_1_2_rpc()
 
494
            else:
 
495
                try:
 
496
                    do_1_2_rpc()
 
497
                except UnknownSmartMethod:
 
498
                    medium._remember_remote_is_before(needed_version)
 
499
                    fallback_to_pre_1_2_rpc()
 
500
 
 
501
        :seealso: _remember_remote_is_before
 
502
        """
 
503
        if self._remote_version_is_before is None:
 
504
            # So far, the remote side seems to support everything
 
505
            return False
 
506
        return version_tuple >= self._remote_version_is_before
 
507
 
 
508
    def _remember_remote_is_before(self, version_tuple):
 
509
        """Tell this medium that the remote side is older the given version.
 
510
 
 
511
        :seealso: _is_remote_before
 
512
        """
 
513
        if (self._remote_version_is_before is not None and
 
514
            version_tuple > self._remote_version_is_before):
 
515
            raise AssertionError(
 
516
                "_remember_remote_is_before(%r) called, but "
 
517
                "_remember_remote_is_before(%r) was called previously."
 
518
                % (version_tuple, self._remote_version_is_before))
 
519
        self._remote_version_is_before = version_tuple
410
520
 
411
521
    def protocol_version(self):
412
 
        """Find out the best protocol version to use."""
 
522
        """Find out if 'hello' smart request works."""
413
523
        if self._protocol_version_error is not None:
414
524
            raise self._protocol_version_error
415
 
        if self._protocol_version is None:
 
525
        if not self._done_hello:
416
526
            try:
417
527
                medium_request = self.get_request()
418
528
                # Send a 'hello' request in protocol version one, for maximum
419
529
                # backwards compatibility.
420
 
                client_protocol = SmartClientRequestProtocolOne(medium_request)
421
 
                self._protocol_version = client_protocol.query_version()
 
530
                client_protocol = protocol.SmartClientRequestProtocolOne(medium_request)
 
531
                client_protocol.query_version()
 
532
                self._done_hello = True
422
533
            except errors.SmartProtocolError, e:
423
534
                # Cache the error, just like we would cache a successful
424
535
                # result.
425
536
                self._protocol_version_error = e
426
537
                raise
427
 
        return self._protocol_version
 
538
        return '2'
 
539
 
 
540
    def should_probe(self):
 
541
        """Should RemoteBzrDirFormat.probe_transport send a smart request on
 
542
        this medium?
 
543
 
 
544
        Some transports are unambiguously smart-only; there's no need to check
 
545
        if the transport is able to carry smart requests, because that's all
 
546
        it is for.  In those cases, this method should return False.
 
547
 
 
548
        But some HTTP transports can sometimes fail to carry smart requests,
 
549
        but still be usuable for accessing remote bzrdirs via plain file
 
550
        accesses.  So for those transports, their media should return True here
 
551
        so that RemoteBzrDirFormat can determine if it is appropriate for that
 
552
        transport.
 
553
        """
 
554
        return False
428
555
 
429
556
    def disconnect(self):
430
557
        """If this medium maintains a persistent connection, close it.
432
559
        The default implementation does nothing.
433
560
        """
434
561
        
 
562
    def remote_path_from_transport(self, transport):
 
563
        """Convert transport into a path suitable for using in a request.
 
564
        
 
565
        Note that the resulting remote path doesn't encode the host name or
 
566
        anything but path, so it is only safe to use it in requests sent over
 
567
        the medium from the matching transport.
 
568
        """
 
569
        medium_base = urlutils.join(self.base, '/')
 
570
        rel_url = urlutils.relative_url(medium_base, transport.base)
 
571
        return urllib.unquote(rel_url)
 
572
 
435
573
 
436
574
class SmartClientStreamMedium(SmartClientMedium):
437
575
    """Stream based medium common class.
442
580
    receive bytes.
443
581
    """
444
582
 
445
 
    def __init__(self):
446
 
        SmartClientMedium.__init__(self)
 
583
    def __init__(self, base):
 
584
        SmartClientMedium.__init__(self, base)
447
585
        self._current_request = None
448
 
        # Be optimistic: we assume the remote end can accept new remote
449
 
        # requests until we get an error saying otherwise.  (1.2 adds some
450
 
        # requests that send bodies, which confuses older servers.)
451
 
        self._remote_is_at_least_1_2 = True
452
586
 
453
587
    def accept_bytes(self, bytes):
454
588
        self._accept_bytes(bytes)
475
609
        """
476
610
        return SmartClientStreamMediumRequest(self)
477
611
 
478
 
    def read_bytes(self, count):
479
 
        return self._read_bytes(count)
480
 
 
481
612
 
482
613
class SmartSimplePipesClientMedium(SmartClientStreamMedium):
483
614
    """A client medium using simple pipes.
485
616
    This client does not manage the pipes: it assumes they will always be open.
486
617
    """
487
618
 
488
 
    def __init__(self, readable_pipe, writeable_pipe):
489
 
        SmartClientStreamMedium.__init__(self)
 
619
    def __init__(self, readable_pipe, writeable_pipe, base):
 
620
        SmartClientStreamMedium.__init__(self, base)
490
621
        self._readable_pipe = readable_pipe
491
622
        self._writeable_pipe = writeable_pipe
492
623
 
507
638
    """A client medium using SSH."""
508
639
    
509
640
    def __init__(self, host, port=None, username=None, password=None,
510
 
            vendor=None, bzr_remote_path=None):
 
641
            base=None, vendor=None, bzr_remote_path=None):
511
642
        """Creates a client that will connect on the first use.
512
643
        
513
644
        :param vendor: An optional override for the ssh vendor to use. See
514
645
            bzrlib.transport.ssh for details on ssh vendors.
515
646
        """
516
 
        SmartClientStreamMedium.__init__(self)
 
647
        SmartClientStreamMedium.__init__(self, base)
517
648
        self._connected = False
518
649
        self._host = host
519
650
        self._password = password
568
699
        """See SmartClientStreamMedium.read_bytes."""
569
700
        if not self._connected:
570
701
            raise errors.MediumNotConnected(self)
571
 
        return self._read_from.read(count)
 
702
        bytes_to_read = min(count, _MAX_READ_SIZE)
 
703
        return self._read_from.read(bytes_to_read)
572
704
 
573
705
 
574
706
# Port 4155 is the default port for bzr://, registered with IANA.
579
711
class SmartTCPClientMedium(SmartClientStreamMedium):
580
712
    """A client medium using TCP."""
581
713
    
582
 
    def __init__(self, host, port):
 
714
    def __init__(self, host, port, base):
583
715
        """Creates a client that will connect on the first use."""
584
 
        SmartClientStreamMedium.__init__(self)
 
716
        SmartClientStreamMedium.__init__(self, base)
585
717
        self._connected = False
586
718
        self._host = host
587
719
        self._port = port
634
766
        """See SmartClientMedium.read_bytes."""
635
767
        if not self._connected:
636
768
            raise errors.MediumNotConnected(self)
637
 
        return self._socket.recv(count)
 
769
        # We ignore the desired_count because on sockets it's more efficient to
 
770
        # read large chunks (of _MAX_READ_SIZE bytes) at a time.
 
771
        return self._socket.recv(_MAX_READ_SIZE)
638
772
 
639
773
 
640
774
class SmartClientStreamMediumRequest(SmartClientMediumRequest):
676
810
        """
677
811
        self._medium._flush()
678
812
 
679
 
    def _read_bytes(self, count):
680
 
        """See SmartClientMediumRequest._read_bytes.
681
 
        
682
 
        This forwards to self._medium._read_bytes because we are operating
683
 
        on the mediums stream.
684
 
        """
685
 
        return self._medium._read_bytes(count)
686