/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
2018.5.19 by Andrew Bennetts
Add docstrings to all the new modules, and a few other places.
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
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
27
import os
28
import socket
2018.5.162 by Andrew Bennetts
Add some missing _ensure_real calls, and a missing import.
29
import sys
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
30
import urllib
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
31
3530.1.1 by John Arbash Meinel
Make bzrlib.smart use lazy imports.
32
from bzrlib.lazy_import import lazy_import
33
lazy_import(globals(), """
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
34
from bzrlib import (
35
    errors,
3118.2.1 by Andrew Bennetts
(andrew) Fix #115781 by passing no more than 64k at a time to socket.sendall.
36
    osutils,
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
37
    symbol_versioning,
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
38
    urlutils,
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
39
    )
3530.1.1 by John Arbash Meinel
Make bzrlib.smart use lazy imports.
40
from bzrlib.smart import protocol
3066.2.1 by John Arbash Meinel
We don't require paramiko for bzr+ssh.
41
from bzrlib.transport import ssh
3530.1.1 by John Arbash Meinel
Make bzrlib.smart use lazy imports.
42
""")
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
43
2018.5.17 by Andrew Bennetts
Paramaterise the commands handled by SmartServerRequestHandler.
44
3565.1.3 by Andrew Bennetts
Define a _MAX_READ_SIZE constant as suggested by John's review.
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
3245.4.16 by Andrew Bennetts
Remove duplication of request version identification logic in wsgi.py
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
    """
3530.1.1 by John Arbash Meinel
Make bzrlib.smart use lazy imports.
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):]
3245.4.16 by Andrew Bennetts
Remove duplication of request version identification logic in wsgi.py
78
    else:
3530.1.1 by John Arbash Meinel
Make bzrlib.smart use lazy imports.
79
        protocol_factory = protocol.SmartServerRequestProtocolOne
3245.4.16 by Andrew Bennetts
Remove duplication of request version identification logic in wsgi.py
80
    return protocol_factory, bytes
81
82
3565.1.1 by Andrew Bennetts
Read no more then 64k at a time in the smart protocol code.
83
class SmartMedium(object):
84
    """Base class for smart protocol media, both client- and server-side."""
85
86
    def __init__(self):
87
        self._push_back_buffer = None
88
        
89
    def _push_back(self, bytes):
90
        """Return unused bytes to the medium, because they belong to the next
91
        request(s).
92
93
        This sets the _push_back_buffer to the given bytes.
94
        """
95
        if self._push_back_buffer is not None:
96
            raise AssertionError(
97
                "_push_back called when self._push_back_buffer is %r"
98
                % (self._push_back_buffer,))
99
        if bytes == '':
100
            return
101
        self._push_back_buffer = bytes
102
103
    def _get_push_back_buffer(self):
104
        if self._push_back_buffer == '':
105
            raise AssertionError(
106
                '%s._push_back_buffer should never be the empty string, '
107
                'which can be confused with EOF' % (self,))
108
        bytes = self._push_back_buffer
109
        self._push_back_buffer = None
110
        return bytes
111
112
    def read_bytes(self, desired_count):
3565.1.2 by Andrew Bennetts
Delete some more code, fix some bugs, add more comments.
113
        """Read some bytes from this medium.
114
115
        :returns: some bytes, possibly more or less than the number requested
116
            in 'desired_count' depending on the medium.
117
        """
118
        if self._push_back_buffer is not None:
119
            return self._get_push_back_buffer()
3565.1.3 by Andrew Bennetts
Define a _MAX_READ_SIZE constant as suggested by John's review.
120
        bytes_to_read = min(desired_count, _MAX_READ_SIZE)
3565.1.1 by Andrew Bennetts
Read no more then 64k at a time in the smart protocol code.
121
        return self._read_bytes(bytes_to_read)
122
123
    def _read_bytes(self, count):
124
        raise NotImplementedError(self._read_bytes)
125
126
    def _get_line(self):
127
        """Read bytes from this request's response until a newline byte.
128
        
129
        This isn't particularly efficient, so should only be used when the
130
        expected size of the line is quite short.
131
132
        :returns: a string of bytes ending in a newline (byte 0x0A).
133
        """
134
        newline_pos = -1
135
        bytes = ''
136
        while newline_pos == -1:
3565.1.2 by Andrew Bennetts
Delete some more code, fix some bugs, add more comments.
137
            new_bytes = self.read_bytes(1)
3565.1.1 by Andrew Bennetts
Read no more then 64k at a time in the smart protocol code.
138
            bytes += new_bytes
139
            if new_bytes == '':
140
                # Ran out of bytes before receiving a complete line.
141
                return bytes
142
            newline_pos = bytes.find('\n')
143
        line = bytes[:newline_pos+1]
144
        self._push_back(bytes[newline_pos+1:])
145
        return line
146
 
147
148
class SmartServerStreamMedium(SmartMedium):
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
149
    """Handles smart commands coming over a stream.
150
151
    The stream may be a pipe connected to sshd, or a tcp socket, or an
152
    in-process fifo for testing.
153
154
    One instance is created for each connected client; it can serve multiple
155
    requests in the lifetime of the connection.
156
157
    The server passes requests through to an underlying backing transport, 
158
    which will typically be a LocalTransport looking at the server's filesystem.
3236.3.4 by Andrew Bennetts
Rename 'push_back' attribute to '_push_back_buffer', add some docstrings, and remove a little bit of redundant code from SmartServerSocketStreamMedium._serve_one_request_unguarded.
159
160
    :ivar _push_back_buffer: a str of bytes that have been read from the stream
161
        but not used yet, or None if there are no buffered bytes.  Subclasses
162
        should make sure to exhaust this buffer before reading more bytes from
163
        the stream.  See also the _push_back method.
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
164
    """
165
2692.1.11 by Andrew Bennetts
Improve test coverage by making SmartTCPServer_for_testing by default create a server that does not serve the backing transport's root at its own root. This mirrors the way most HTTP smart servers are configured.
166
    def __init__(self, backing_transport, root_client_path='/'):
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
167
        """Construct new server.
168
169
        :param backing_transport: Transport for the directory served.
170
        """
171
        # backing_transport could be passed to serve instead of __init__
172
        self.backing_transport = backing_transport
2692.1.11 by Andrew Bennetts
Improve test coverage by making SmartTCPServer_for_testing by default create a server that does not serve the backing transport's root at its own root. This mirrors the way most HTTP smart servers are configured.
173
        self.root_client_path = root_client_path
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
174
        self.finished = False
3565.1.1 by Andrew Bennetts
Read no more then 64k at a time in the smart protocol code.
175
        SmartMedium.__init__(self)
3236.3.5 by Andrew Bennetts
Add _get_push_back_buffer helper.
176
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
177
    def serve(self):
178
        """Serve requests until the client disconnects."""
179
        # Keep a reference to stderr because the sys module's globals get set to
180
        # None during interpreter shutdown.
181
        from sys import stderr
182
        try:
183
            while not self.finished:
2432.2.3 by Andrew Bennetts
Merge from bzr.dev.
184
                server_protocol = self._build_protocol()
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
185
                self._serve_one_request(server_protocol)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
186
        except Exception, e:
187
            stderr.write("%s terminating on exception %s\n" % (self, e))
188
            raise
189
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
190
    def _build_protocol(self):
2432.2.8 by Andrew Bennetts
NEWS entry, greatly improved docstring in bzrlib.smart.
191
        """Identifies the version of the incoming request, and returns an
192
        a protocol object that can interpret it.
193
194
        If more bytes than the version prefix of the request are read, they will
195
        be fed into the protocol before it is returned.
196
197
        :returns: a SmartServerRequestProtocol.
198
        """
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
199
        bytes = self._get_line()
3245.4.16 by Andrew Bennetts
Remove duplication of request version identification logic in wsgi.py
200
        protocol_factory, unused_bytes = _get_protocol_factory_for_bytes(bytes)
3245.4.14 by Andrew Bennetts
Merge from bzr.dev (via loom thread).
201
        protocol = protocol_factory(
2692.1.11 by Andrew Bennetts
Improve test coverage by making SmartTCPServer_for_testing by default create a server that does not serve the backing transport's root at its own root. This mirrors the way most HTTP smart servers are configured.
202
            self.backing_transport, self._write_out, self.root_client_path)
3245.4.16 by Andrew Bennetts
Remove duplication of request version identification logic in wsgi.py
203
        protocol.accept_bytes(unused_bytes)
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
204
        return protocol
205
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
206
    def _serve_one_request(self, protocol):
207
        """Read one request from input, process, send back a response.
208
        
209
        :param protocol: a SmartServerRequestProtocol.
210
        """
211
        try:
212
            self._serve_one_request_unguarded(protocol)
213
        except KeyboardInterrupt:
214
            raise
215
        except Exception, e:
216
            self.terminate_due_to_error()
217
218
    def terminate_due_to_error(self):
219
        """Called when an unhandled exception from the protocol occurs."""
220
        raise NotImplementedError(self.terminate_due_to_error)
221
3565.1.2 by Andrew Bennetts
Delete some more code, fix some bugs, add more comments.
222
    def _read_bytes(self, desired_count):
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
223
        """Get some bytes from the medium.
224
225
        :param desired_count: number of bytes we want to read.
226
        """
3565.1.2 by Andrew Bennetts
Delete some more code, fix some bugs, add more comments.
227
        raise NotImplementedError(self._read_bytes)
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
228
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
229
230
class SmartServerSocketStreamMedium(SmartServerStreamMedium):
231
2692.1.11 by Andrew Bennetts
Improve test coverage by making SmartTCPServer_for_testing by default create a server that does not serve the backing transport's root at its own root. This mirrors the way most HTTP smart servers are configured.
232
    def __init__(self, sock, backing_transport, root_client_path='/'):
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
233
        """Constructor.
234
235
        :param sock: the socket the server will read from.  It will be put
236
            into blocking mode.
237
        """
2692.1.11 by Andrew Bennetts
Improve test coverage by making SmartTCPServer_for_testing by default create a server that does not serve the backing transport's root at its own root. This mirrors the way most HTTP smart servers are configured.
238
        SmartServerStreamMedium.__init__(
239
            self, backing_transport, root_client_path=root_client_path)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
240
        sock.setblocking(True)
241
        self.socket = sock
242
243
    def _serve_one_request_unguarded(self, protocol):
244
        while protocol.next_read_size():
3565.1.3 by Andrew Bennetts
Define a _MAX_READ_SIZE constant as suggested by John's review.
245
            # We can safely try to read large chunks.  If there is less data
246
            # than _MAX_READ_SIZE ready, the socket wil just return a short
247
            # read immediately rather than block.
248
            bytes = self.read_bytes(_MAX_READ_SIZE)
3236.3.4 by Andrew Bennetts
Rename 'push_back' attribute to '_push_back_buffer', add some docstrings, and remove a little bit of redundant code from SmartServerSocketStreamMedium._serve_one_request_unguarded.
249
            if bytes == '':
250
                self.finished = True
251
                return
252
            protocol.accept_bytes(bytes)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
253
        
3245.4.21 by Andrew Bennetts
Remove 'excess_buffer' attribute and another crufty comment.
254
        self._push_back(protocol.unused_data)
3195.3.18 by Andrew Bennetts
call_with_body_bytes now works with v3 (e.g. test_copy_content_remote_to_local passes). Lots of debugging cruft, though.
255
3565.1.2 by Andrew Bennetts
Delete some more code, fix some bugs, add more comments.
256
    def _read_bytes(self, desired_count):
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
257
        # We ignore the desired_count because on sockets it's more efficient to
3565.1.3 by Andrew Bennetts
Define a _MAX_READ_SIZE constant as suggested by John's review.
258
        # read large chunks (of _MAX_READ_SIZE bytes) at a time.
259
        return self.socket.recv(_MAX_READ_SIZE)
3565.1.1 by Andrew Bennetts
Read no more then 64k at a time in the smart protocol code.
260
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
261
    def terminate_due_to_error(self):
3245.4.59 by Andrew Bennetts
Various tweaks in response to Martin's review.
262
        # TODO: This should log to a server log file, but no such thing
263
        # exists yet.  Andrew Bennetts 2006-09-29.
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
264
        self.socket.close()
265
        self.finished = True
266
267
    def _write_out(self, bytes):
3118.2.1 by Andrew Bennetts
(andrew) Fix #115781 by passing no more than 64k at a time to socket.sendall.
268
        osutils.send_all(self.socket, bytes)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
269
270
271
class SmartServerPipeStreamMedium(SmartServerStreamMedium):
272
273
    def __init__(self, in_file, out_file, backing_transport):
274
        """Construct new server.
275
276
        :param in_file: Python file from which requests can be read.
277
        :param out_file: Python file to write responses.
278
        :param backing_transport: Transport for the directory served.
279
        """
280
        SmartServerStreamMedium.__init__(self, backing_transport)
2018.5.161 by Andrew Bennetts
Reinstate forcing binary mode on windows in SmartServerStreamMedium.
281
        if sys.platform == 'win32':
282
            # force binary mode for files
283
            import msvcrt
284
            for f in (in_file, out_file):
285
                fileno = getattr(f, 'fileno', None)
286
                if fileno:
287
                    msvcrt.setmode(fileno(), os.O_BINARY)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
288
        self._in = in_file
289
        self._out = out_file
290
291
    def _serve_one_request_unguarded(self, protocol):
292
        while True:
3565.1.2 by Andrew Bennetts
Delete some more code, fix some bugs, add more comments.
293
            # We need to be careful not to read past the end of the current
294
            # request, or else the read from the pipe will block, so we use
295
            # protocol.next_read_size().
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
296
            bytes_to_read = protocol.next_read_size()
297
            if bytes_to_read == 0:
298
                # Finished serving this request.
299
                self._out.flush()
300
                return
3565.1.2 by Andrew Bennetts
Delete some more code, fix some bugs, add more comments.
301
            bytes = self.read_bytes(bytes_to_read)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
302
            if bytes == '':
303
                # Connection has been closed.
304
                self.finished = True
305
                self._out.flush()
306
                return
307
            protocol.accept_bytes(bytes)
308
3565.1.2 by Andrew Bennetts
Delete some more code, fix some bugs, add more comments.
309
    def _read_bytes(self, desired_count):
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
310
        return self._in.read(desired_count)
311
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
312
    def terminate_due_to_error(self):
313
        # TODO: This should log to a server log file, but no such thing
314
        # exists yet.  Andrew Bennetts 2006-09-29.
315
        self._out.close()
316
        self.finished = True
317
318
    def _write_out(self, bytes):
319
        self._out.write(bytes)
320
321
3565.1.2 by Andrew Bennetts
Delete some more code, fix some bugs, add more comments.
322
class SmartClientMediumRequest(object):
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
323
    """A request on a SmartClientMedium.
324
325
    Each request allows bytes to be provided to it via accept_bytes, and then
326
    the response bytes to be read via read_bytes.
327
328
    For instance:
329
    request.accept_bytes('123')
330
    request.finished_writing()
331
    result = request.read_bytes(3)
332
    request.finished_reading()
333
334
    It is up to the individual SmartClientMedium whether multiple concurrent
335
    requests can exist. See SmartClientMedium.get_request to obtain instances 
336
    of SmartClientMediumRequest, and the concrete Medium you are using for 
337
    details on concurrency and pipelining.
338
    """
339
340
    def __init__(self, medium):
341
        """Construct a SmartClientMediumRequest for the medium medium."""
342
        self._medium = medium
343
        # we track state by constants - we may want to use the same
344
        # pattern as BodyReader if it gets more complex.
345
        # valid states are: "writing", "reading", "done"
346
        self._state = "writing"
347
348
    def accept_bytes(self, bytes):
349
        """Accept bytes for inclusion in this request.
350
351
        This method may not be be called after finished_writing() has been
352
        called.  It depends upon the Medium whether or not the bytes will be
353
        immediately transmitted. Message based Mediums will tend to buffer the
354
        bytes until finished_writing() is called.
355
356
        :param bytes: A bytestring.
357
        """
358
        if self._state != "writing":
359
            raise errors.WritingCompleted(self)
360
        self._accept_bytes(bytes)
361
362
    def _accept_bytes(self, bytes):
363
        """Helper for accept_bytes.
364
365
        Accept_bytes checks the state of the request to determing if bytes
366
        should be accepted. After that it hands off to _accept_bytes to do the
367
        actual acceptance.
368
        """
369
        raise NotImplementedError(self._accept_bytes)
370
371
    def finished_reading(self):
372
        """Inform the request that all desired data has been read.
373
374
        This will remove the request from the pipeline for its medium (if the
375
        medium supports pipelining) and any further calls to methods on the
376
        request will raise ReadingCompleted.
377
        """
378
        if self._state == "writing":
379
            raise errors.WritingNotComplete(self)
380
        if self._state != "reading":
381
            raise errors.ReadingCompleted(self)
382
        self._state = "done"
383
        self._finished_reading()
384
385
    def _finished_reading(self):
386
        """Helper for finished_reading.
387
388
        finished_reading checks the state of the request to determine if 
389
        finished_reading is allowed, and if it is hands off to _finished_reading
390
        to perform the action.
391
        """
392
        raise NotImplementedError(self._finished_reading)
393
394
    def finished_writing(self):
395
        """Finish the writing phase of this request.
396
397
        This will flush all pending data for this request along the medium.
398
        After calling finished_writing, you may not call accept_bytes anymore.
399
        """
400
        if self._state != "writing":
401
            raise errors.WritingCompleted(self)
402
        self._state = "reading"
403
        self._finished_writing()
404
405
    def _finished_writing(self):
406
        """Helper for finished_writing.
407
408
        finished_writing checks the state of the request to determine if 
409
        finished_writing is allowed, and if it is hands off to _finished_writing
410
        to perform the action.
411
        """
412
        raise NotImplementedError(self._finished_writing)
413
414
    def read_bytes(self, count):
415
        """Read bytes from this requests response.
416
417
        This method will block and wait for count bytes to be read. It may not
418
        be invoked until finished_writing() has been called - this is to ensure
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
419
        a message-based approach to requests, for compatibility with message
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
420
        based mediums like HTTP.
421
        """
422
        if self._state == "writing":
423
            raise errors.WritingNotComplete(self)
424
        if self._state != "reading":
425
            raise errors.ReadingCompleted(self)
426
        return self._read_bytes(count)
427
428
    def _read_bytes(self, count):
3565.1.2 by Andrew Bennetts
Delete some more code, fix some bugs, add more comments.
429
        """Helper for SmartClientMediumRequest.read_bytes.
430
431
        read_bytes checks the state of the request to determing if bytes
432
        should be read. After that it hands off to _read_bytes to do the
433
        actual read.
3565.1.1 by Andrew Bennetts
Read no more then 64k at a time in the smart protocol code.
434
        
3565.1.2 by Andrew Bennetts
Delete some more code, fix some bugs, add more comments.
435
        By default this forwards to self._medium.read_bytes because we are
436
        operating on the medium's stream.
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
437
        """
3565.1.2 by Andrew Bennetts
Delete some more code, fix some bugs, add more comments.
438
        return self._medium.read_bytes(count)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
439
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
440
    def read_line(self):
3565.1.1 by Andrew Bennetts
Read no more then 64k at a time in the smart protocol code.
441
        line = self._medium._get_line()
442
        if not line.endswith('\n'):
443
            # end of file encountered reading from server
444
            raise errors.ConnectionReset(
445
                "please check connectivity and permissions",
446
                "(and try -Dhpss if further diagnosis is required)")
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
447
        return line
448
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
449
3565.1.1 by Andrew Bennetts
Read no more then 64k at a time in the smart protocol code.
450
class SmartClientMedium(SmartMedium):
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
451
    """Smart client is a medium for sending smart protocol requests over."""
452
3431.3.3 by Andrew Bennetts
Set 'base' in SmartClientMedium base class.
453
    def __init__(self, base):
3241.1.1 by Andrew Bennetts
Shift protocol version querying from RemoteBzrDirFormat into SmartClientMedium.
454
        super(SmartClientMedium, self).__init__()
3431.3.3 by Andrew Bennetts
Set 'base' in SmartClientMedium base class.
455
        self.base = base
3241.1.4 by Andrew Bennetts
Use get_smart_medium as suggested by Robert, and deal with the fallout.
456
        self._protocol_version_error = None
3241.1.1 by Andrew Bennetts
Shift protocol version querying from RemoteBzrDirFormat into SmartClientMedium.
457
        self._protocol_version = None
3245.4.47 by Andrew Bennetts
Don't automatically send 'hello' requests from RemoteBzrDirFormat.probe_transport unless we have to (i.e. the transport is HTTP).
458
        self._done_hello = False
3435.1.1 by Andrew Bennetts
Define _remote_is_at_least_1_2 on SmartClientMedium base class, rather than just SmartClientStreamMedium.
459
        # Be optimistic: we assume the remote end can accept new remote
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
460
        # requests until we get an error saying otherwise.
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
461
        # _remote_version_is_before tracks the bzr version the remote side
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
462
        # can be based on what we've seen so far.
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
463
        self._remote_version_is_before = None
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
464
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
465
    def _is_remote_before(self, version_tuple):
3502.1.1 by Matt Nordhoff
Fix a docstring typo, and a two-expression ``raise`` statement
466
        """Is it possible the remote side supports RPCs for a given version?
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
467
468
        Typical use::
469
470
            needed_version = (1, 2)
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
471
            if medium._is_remote_before(needed_version):
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
472
                fallback_to_pre_1_2_rpc()
473
            else:
474
                try:
475
                    do_1_2_rpc()
476
                except UnknownSmartMethod:
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
477
                    medium._remember_remote_is_before(needed_version)
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
478
                    fallback_to_pre_1_2_rpc()
479
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
480
        :seealso: _remember_remote_is_before
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
481
        """
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
482
        if self._remote_version_is_before is None:
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
483
            # So far, the remote side seems to support everything
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
484
            return False
485
        return version_tuple >= self._remote_version_is_before
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
486
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
487
    def _remember_remote_is_before(self, version_tuple):
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
488
        """Tell this medium that the remote side is older the given version.
489
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
490
        :seealso: _is_remote_before
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
491
        """
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
492
        if (self._remote_version_is_before is not None and
493
            version_tuple > self._remote_version_is_before):
3502.1.1 by Matt Nordhoff
Fix a docstring typo, and a two-expression ``raise`` statement
494
            raise AssertionError(
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
495
                "_remember_remote_is_before(%r) called, but "
496
                "_remember_remote_is_before(%r) was called previously."
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
497
                % (version_tuple, self._remote_version_is_before))
498
        self._remote_version_is_before = version_tuple
3241.1.1 by Andrew Bennetts
Shift protocol version querying from RemoteBzrDirFormat into SmartClientMedium.
499
500
    def protocol_version(self):
3245.4.47 by Andrew Bennetts
Don't automatically send 'hello' requests from RemoteBzrDirFormat.probe_transport unless we have to (i.e. the transport is HTTP).
501
        """Find out if 'hello' smart request works."""
3241.1.4 by Andrew Bennetts
Use get_smart_medium as suggested by Robert, and deal with the fallout.
502
        if self._protocol_version_error is not None:
503
            raise self._protocol_version_error
3245.4.47 by Andrew Bennetts
Don't automatically send 'hello' requests from RemoteBzrDirFormat.probe_transport unless we have to (i.e. the transport is HTTP).
504
        if not self._done_hello:
3241.1.4 by Andrew Bennetts
Use get_smart_medium as suggested by Robert, and deal with the fallout.
505
            try:
506
                medium_request = self.get_request()
507
                # Send a 'hello' request in protocol version one, for maximum
508
                # backwards compatibility.
3530.1.2 by John Arbash Meinel
missed one of the imports
509
                client_protocol = protocol.SmartClientRequestProtocolOne(medium_request)
3245.4.47 by Andrew Bennetts
Don't automatically send 'hello' requests from RemoteBzrDirFormat.probe_transport unless we have to (i.e. the transport is HTTP).
510
                client_protocol.query_version()
511
                self._done_hello = True
3241.1.4 by Andrew Bennetts
Use get_smart_medium as suggested by Robert, and deal with the fallout.
512
            except errors.SmartProtocolError, e:
513
                # Cache the error, just like we would cache a successful
514
                # result.
515
                self._protocol_version_error = e
516
                raise
3245.4.47 by Andrew Bennetts
Don't automatically send 'hello' requests from RemoteBzrDirFormat.probe_transport unless we have to (i.e. the transport is HTTP).
517
        return '2'
518
519
    def should_probe(self):
520
        """Should RemoteBzrDirFormat.probe_transport send a smart request on
521
        this medium?
522
523
        Some transports are unambiguously smart-only; there's no need to check
524
        if the transport is able to carry smart requests, because that's all
525
        it is for.  In those cases, this method should return False.
526
527
        But some HTTP transports can sometimes fail to carry smart requests,
528
        but still be usuable for accessing remote bzrdirs via plain file
529
        accesses.  So for those transports, their media should return True here
530
        so that RemoteBzrDirFormat can determine if it is appropriate for that
531
        transport.
532
        """
533
        return False
3241.1.1 by Andrew Bennetts
Shift protocol version querying from RemoteBzrDirFormat into SmartClientMedium.
534
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
535
    def disconnect(self):
536
        """If this medium maintains a persistent connection, close it.
537
        
538
        The default implementation does nothing.
539
        """
540
        
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
541
    def remote_path_from_transport(self, transport):
542
        """Convert transport into a path suitable for using in a request.
543
        
544
        Note that the resulting remote path doesn't encode the host name or
545
        anything but path, so it is only safe to use it in requests sent over
546
        the medium from the matching transport.
547
        """
548
        medium_base = urlutils.join(self.base, '/')
549
        rel_url = urlutils.relative_url(medium_base, transport.base)
550
        return urllib.unquote(rel_url)
551
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
552
553
class SmartClientStreamMedium(SmartClientMedium):
554
    """Stream based medium common class.
555
556
    SmartClientStreamMediums operate on a stream. All subclasses use a common
557
    SmartClientStreamMediumRequest for their requests, and should implement
558
    _accept_bytes and _read_bytes to allow the request objects to send and
559
    receive bytes.
560
    """
561
3431.3.3 by Andrew Bennetts
Set 'base' in SmartClientMedium base class.
562
    def __init__(self, base):
563
        SmartClientMedium.__init__(self, base)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
564
        self._current_request = None
565
566
    def accept_bytes(self, bytes):
567
        self._accept_bytes(bytes)
568
569
    def __del__(self):
570
        """The SmartClientStreamMedium knows how to close the stream when it is
571
        finished with it.
572
        """
573
        self.disconnect()
574
575
    def _flush(self):
576
        """Flush the output stream.
577
        
578
        This method is used by the SmartClientStreamMediumRequest to ensure that
579
        all data for a request is sent, to avoid long timeouts or deadlocks.
580
        """
581
        raise NotImplementedError(self._flush)
582
583
    def get_request(self):
584
        """See SmartClientMedium.get_request().
585
586
        SmartClientStreamMedium always returns a SmartClientStreamMediumRequest
587
        for get_request.
588
        """
589
        return SmartClientStreamMediumRequest(self)
590
591
592
class SmartSimplePipesClientMedium(SmartClientStreamMedium):
593
    """A client medium using simple pipes.
594
    
595
    This client does not manage the pipes: it assumes they will always be open.
596
    """
597
3431.3.1 by Andrew Bennetts
First rough cut of a fix for bug #230550, by adding .base to SmartClientMedia rather than relying on other objects to track this accurately while reusing client media.
598
    def __init__(self, readable_pipe, writeable_pipe, base):
3431.3.3 by Andrew Bennetts
Set 'base' in SmartClientMedium base class.
599
        SmartClientStreamMedium.__init__(self, base)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
600
        self._readable_pipe = readable_pipe
601
        self._writeable_pipe = writeable_pipe
602
603
    def _accept_bytes(self, bytes):
604
        """See SmartClientStreamMedium.accept_bytes."""
605
        self._writeable_pipe.write(bytes)
606
607
    def _flush(self):
608
        """See SmartClientStreamMedium._flush()."""
609
        self._writeable_pipe.flush()
610
611
    def _read_bytes(self, count):
612
        """See SmartClientStreamMedium._read_bytes."""
613
        return self._readable_pipe.read(count)
614
615
616
class SmartSSHClientMedium(SmartClientStreamMedium):
617
    """A client medium using SSH."""
618
    
619
    def __init__(self, host, port=None, username=None, password=None,
3431.3.1 by Andrew Bennetts
First rough cut of a fix for bug #230550, by adding .base to SmartClientMedia rather than relying on other objects to track this accurately while reusing client media.
620
            base=None, vendor=None, bzr_remote_path=None):
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
621
        """Creates a client that will connect on the first use.
622
        
623
        :param vendor: An optional override for the ssh vendor to use. See
624
            bzrlib.transport.ssh for details on ssh vendors.
625
        """
3431.3.3 by Andrew Bennetts
Set 'base' in SmartClientMedium base class.
626
        SmartClientStreamMedium.__init__(self, base)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
627
        self._connected = False
628
        self._host = host
629
        self._password = password
630
        self._port = port
631
        self._username = username
632
        self._read_from = None
633
        self._ssh_connection = None
634
        self._vendor = vendor
635
        self._write_to = None
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
636
        self._bzr_remote_path = bzr_remote_path
637
        if self._bzr_remote_path is None:
638
            symbol_versioning.warn(
639
                'bzr_remote_path is required as of bzr 0.92',
640
                DeprecationWarning, stacklevel=2)
641
            self._bzr_remote_path = os.environ.get('BZR_REMOTE_PATH', 'bzr')
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
642
643
    def _accept_bytes(self, bytes):
644
        """See SmartClientStreamMedium.accept_bytes."""
645
        self._ensure_connection()
646
        self._write_to.write(bytes)
647
648
    def disconnect(self):
649
        """See SmartClientMedium.disconnect()."""
650
        if not self._connected:
651
            return
652
        self._read_from.close()
653
        self._write_to.close()
654
        self._ssh_connection.close()
655
        self._connected = False
656
657
    def _ensure_connection(self):
658
        """Connect this medium if not already connected."""
659
        if self._connected:
660
            return
661
        if self._vendor is None:
662
            vendor = ssh._get_ssh_vendor()
663
        else:
664
            vendor = self._vendor
665
        self._ssh_connection = vendor.connect_ssh(self._username,
666
                self._password, self._host, self._port,
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
667
                command=[self._bzr_remote_path, 'serve', '--inet',
668
                         '--directory=/', '--allow-writes'])
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
669
        self._read_from, self._write_to = \
670
            self._ssh_connection.get_filelike_channels()
671
        self._connected = True
672
673
    def _flush(self):
674
        """See SmartClientStreamMedium._flush()."""
675
        self._write_to.flush()
676
677
    def _read_bytes(self, count):
678
        """See SmartClientStreamMedium.read_bytes."""
679
        if not self._connected:
680
            raise errors.MediumNotConnected(self)
3565.1.3 by Andrew Bennetts
Define a _MAX_READ_SIZE constant as suggested by John's review.
681
        bytes_to_read = min(count, _MAX_READ_SIZE)
3565.1.1 by Andrew Bennetts
Read no more then 64k at a time in the smart protocol code.
682
        return self._read_from.read(bytes_to_read)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
683
684
3004.2.1 by Vincent Ladeuil
Fix 150860 by leaving port as user specified it.
685
# Port 4155 is the default port for bzr://, registered with IANA.
686
BZR_DEFAULT_INTERFACE = '0.0.0.0'
687
BZR_DEFAULT_PORT = 4155
688
689
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
690
class SmartTCPClientMedium(SmartClientStreamMedium):
691
    """A client medium using TCP."""
692
    
3431.3.1 by Andrew Bennetts
First rough cut of a fix for bug #230550, by adding .base to SmartClientMedia rather than relying on other objects to track this accurately while reusing client media.
693
    def __init__(self, host, port, base):
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
694
        """Creates a client that will connect on the first use."""
3431.3.3 by Andrew Bennetts
Set 'base' in SmartClientMedium base class.
695
        SmartClientStreamMedium.__init__(self, base)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
696
        self._connected = False
697
        self._host = host
698
        self._port = port
699
        self._socket = None
700
701
    def _accept_bytes(self, bytes):
702
        """See SmartClientMedium.accept_bytes."""
703
        self._ensure_connection()
3118.2.1 by Andrew Bennetts
(andrew) Fix #115781 by passing no more than 64k at a time to socket.sendall.
704
        osutils.send_all(self._socket, bytes)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
705
706
    def disconnect(self):
707
        """See SmartClientMedium.disconnect()."""
708
        if not self._connected:
709
            return
710
        self._socket.close()
711
        self._socket = None
712
        self._connected = False
713
714
    def _ensure_connection(self):
715
        """Connect this medium if not already connected."""
716
        if self._connected:
717
            return
718
        self._socket = socket.socket()
719
        self._socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
3004.2.1 by Vincent Ladeuil
Fix 150860 by leaving port as user specified it.
720
        if self._port is None:
721
            port = BZR_DEFAULT_PORT
722
        else:
723
            port = int(self._port)
3180.1.1 by Andrew Bennetts
Don't traceback on host name errors when connecting to bzr://...
724
        try:
725
            self._socket.connect((self._host, port))
726
        except socket.error, err:
727
            # socket errors either have a (string) or (errno, string) as their
728
            # args.
729
            if type(err.args) is str:
730
                err_msg = err.args
731
            else:
732
                err_msg = err.args[1]
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
733
            raise errors.ConnectionError("failed to connect to %s:%d: %s" %
3180.1.1 by Andrew Bennetts
Don't traceback on host name errors when connecting to bzr://...
734
                    (self._host, port, err_msg))
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
735
        self._connected = True
736
737
    def _flush(self):
738
        """See SmartClientStreamMedium._flush().
739
        
740
        For TCP we do no flushing. We may want to turn off TCP_NODELAY and 
741
        add a means to do a flush, but that can be done in the future.
742
        """
743
744
    def _read_bytes(self, count):
745
        """See SmartClientMedium.read_bytes."""
746
        if not self._connected:
747
            raise errors.MediumNotConnected(self)
3565.1.3 by Andrew Bennetts
Define a _MAX_READ_SIZE constant as suggested by John's review.
748
        # We ignore the desired_count because on sockets it's more efficient to
749
        # read large chunks (of _MAX_READ_SIZE bytes) at a time.
750
        return self._socket.recv(_MAX_READ_SIZE)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
751
752
753
class SmartClientStreamMediumRequest(SmartClientMediumRequest):
754
    """A SmartClientMediumRequest that works with an SmartClientStreamMedium."""
755
756
    def __init__(self, medium):
757
        SmartClientMediumRequest.__init__(self, medium)
758
        # check that we are safe concurrency wise. If some streams start
759
        # allowing concurrent requests - i.e. via multiplexing - then this
760
        # assert should be moved to SmartClientStreamMedium.get_request,
761
        # and the setting/unsetting of _current_request likewise moved into
762
        # that class : but its unneeded overhead for now. RBC 20060922
763
        if self._medium._current_request is not None:
764
            raise errors.TooManyConcurrentRequests(self._medium)
765
        self._medium._current_request = self
766
767
    def _accept_bytes(self, bytes):
768
        """See SmartClientMediumRequest._accept_bytes.
769
        
770
        This forwards to self._medium._accept_bytes because we are operating
771
        on the mediums stream.
772
        """
773
        self._medium._accept_bytes(bytes)
774
775
    def _finished_reading(self):
776
        """See SmartClientMediumRequest._finished_reading.
777
778
        This clears the _current_request on self._medium to allow a new 
779
        request to be created.
780
        """
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
781
        if self._medium._current_request is not self:
782
            raise AssertionError()
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
783
        self._medium._current_request = None
784
        
785
    def _finished_writing(self):
786
        """See SmartClientMediumRequest._finished_writing.
787
788
        This invokes self._medium._flush to ensure all bytes are transmitted.
789
        """
790
        self._medium._flush()
791