/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
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
30
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
31
from bzrlib import (
32
    errors,
3118.2.1 by Andrew Bennetts
(andrew) Fix #115781 by passing no more than 64k at a time to socket.sendall.
33
    osutils,
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
34
    symbol_versioning,
35
    )
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
36
from bzrlib.smart.protocol import (
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
37
    MESSAGE_VERSION_THREE,
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
38
    REQUEST_VERSION_TWO,
3241.1.1 by Andrew Bennetts
Shift protocol version querying from RemoteBzrDirFormat into SmartClientMedium.
39
    SmartClientRequestProtocolOne,
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
40
    SmartServerRequestProtocolOne,
41
    SmartServerRequestProtocolTwo,
3195.3.17 by Andrew Bennetts
Some tests now passing using protocol 3.
42
    build_server_protocol_three
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
43
    )
3066.2.1 by John Arbash Meinel
We don't require paramiko for bzr+ssh.
44
from bzrlib.transport import ssh
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
45
2018.5.17 by Andrew Bennetts
Paramaterise the commands handled by SmartServerRequestHandler.
46
3245.4.16 by Andrew Bennetts
Remove duplication of request version identification logic in wsgi.py
47
def _get_protocol_factory_for_bytes(bytes):
48
    """Determine the right protocol factory for 'bytes'.
49
50
    This will return an appropriate protocol factory depending on the version
51
    of the protocol being used, as determined by inspecting the given bytes.
52
    The bytes should have at least one newline byte (i.e. be a whole line),
53
    otherwise it's possible that a request will be incorrectly identified as
54
    version 1.
55
56
    Typical use would be::
57
58
         factory, unused_bytes = _get_protocol_factory_for_bytes(bytes)
59
         server_protocol = factory(transport, write_func, root_client_path)
60
         server_protocol.accept_bytes(unused_bytes)
61
62
    :param bytes: a str of bytes of the start of the request.
63
    :returns: 2-tuple of (protocol_factory, unused_bytes).  protocol_factory is
64
        a callable that takes three args: transport, write_func,
65
        root_client_path.  unused_bytes are any bytes that were not part of a
66
        protocol version marker.
67
    """
68
    if bytes.startswith(MESSAGE_VERSION_THREE):
69
        protocol_factory = build_server_protocol_three
70
        bytes = bytes[len(MESSAGE_VERSION_THREE):]
71
    elif bytes.startswith(REQUEST_VERSION_TWO):
72
        protocol_factory = SmartServerRequestProtocolTwo
73
        bytes = bytes[len(REQUEST_VERSION_TWO):]
74
    else:
75
        protocol_factory = SmartServerRequestProtocolOne
76
    return protocol_factory, bytes
77
78
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
79
class SmartServerStreamMedium(object):
80
    """Handles smart commands coming over a stream.
81
82
    The stream may be a pipe connected to sshd, or a tcp socket, or an
83
    in-process fifo for testing.
84
85
    One instance is created for each connected client; it can serve multiple
86
    requests in the lifetime of the connection.
87
88
    The server passes requests through to an underlying backing transport, 
89
    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.
90
91
    :ivar _push_back_buffer: a str of bytes that have been read from the stream
92
        but not used yet, or None if there are no buffered bytes.  Subclasses
93
        should make sure to exhaust this buffer before reading more bytes from
94
        the stream.  See also the _push_back method.
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
95
    """
96
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.
97
    def __init__(self, backing_transport, root_client_path='/'):
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
98
        """Construct new server.
99
100
        :param backing_transport: Transport for the directory served.
101
        """
102
        # backing_transport could be passed to serve instead of __init__
103
        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.
104
        self.root_client_path = root_client_path
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
105
        self.finished = False
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.
106
        self._push_back_buffer = None
3236.3.2 by Andrew Bennetts
Fix SmartServerPipeStreamMedium._get_line too.
107
108
    def _push_back(self, bytes):
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.
109
        """Return unused bytes to the medium, because they belong to the next
110
        request(s).
111
112
        This sets the _push_back_buffer to the given bytes.
113
        """
114
        assert self._push_back_buffer is None, (
115
            "_push_back called when self._push_back_buffer is %r"
116
            % (self._push_back_buffer,))
3236.3.2 by Andrew Bennetts
Fix SmartServerPipeStreamMedium._get_line too.
117
        if bytes == '':
118
            return
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.
119
        self._push_back_buffer = bytes
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
120
3236.3.5 by Andrew Bennetts
Add _get_push_back_buffer helper.
121
    def _get_push_back_buffer(self):
122
        assert self._push_back_buffer != '', (
123
            '%s._push_back_buffer should never be the empty string, '
124
            'which can be confused with EOF' % (self,))
125
        bytes = self._push_back_buffer
126
        self._push_back_buffer = None
127
        return bytes
128
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
129
    def serve(self):
130
        """Serve requests until the client disconnects."""
131
        # Keep a reference to stderr because the sys module's globals get set to
132
        # None during interpreter shutdown.
133
        from sys import stderr
134
        try:
135
            while not self.finished:
2432.2.3 by Andrew Bennetts
Merge from bzr.dev.
136
                server_protocol = self._build_protocol()
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
137
                self._serve_one_request(server_protocol)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
138
        except Exception, e:
139
            stderr.write("%s terminating on exception %s\n" % (self, e))
140
            raise
141
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
142
    def _build_protocol(self):
2432.2.8 by Andrew Bennetts
NEWS entry, greatly improved docstring in bzrlib.smart.
143
        """Identifies the version of the incoming request, and returns an
144
        a protocol object that can interpret it.
145
146
        If more bytes than the version prefix of the request are read, they will
147
        be fed into the protocol before it is returned.
148
149
        :returns: a SmartServerRequestProtocol.
150
        """
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
151
        bytes = self._get_line()
3245.4.16 by Andrew Bennetts
Remove duplication of request version identification logic in wsgi.py
152
        protocol_factory, unused_bytes = _get_protocol_factory_for_bytes(bytes)
3245.4.14 by Andrew Bennetts
Merge from bzr.dev (via loom thread).
153
        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.
154
            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
155
        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.
156
        return protocol
157
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
158
    def _serve_one_request(self, protocol):
159
        """Read one request from input, process, send back a response.
160
        
161
        :param protocol: a SmartServerRequestProtocol.
162
        """
163
        try:
164
            self._serve_one_request_unguarded(protocol)
165
        except KeyboardInterrupt:
166
            raise
167
        except Exception, e:
168
            self.terminate_due_to_error()
169
170
    def terminate_due_to_error(self):
171
        """Called when an unhandled exception from the protocol occurs."""
172
        raise NotImplementedError(self.terminate_due_to_error)
173
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
174
    def _get_bytes(self, desired_count):
175
        """Get some bytes from the medium.
176
177
        :param desired_count: number of bytes we want to read.
178
        """
179
        raise NotImplementedError(self._get_bytes)
180
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
181
    def _get_line(self):
182
        """Read bytes from this request's response until a newline byte.
183
        
184
        This isn't particularly efficient, so should only be used when the
185
        expected size of the line is quite short.
186
187
        :returns: a string of bytes ending in a newline (byte 0x0A).
188
        """
3236.3.2 by Andrew Bennetts
Fix SmartServerPipeStreamMedium._get_line too.
189
        newline_pos = -1
190
        bytes = ''
191
        while newline_pos == -1:
192
            new_bytes = self._get_bytes(1)
193
            bytes += new_bytes
194
            if new_bytes == '':
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
195
                # Ran out of bytes before receiving a complete line.
3236.3.2 by Andrew Bennetts
Fix SmartServerPipeStreamMedium._get_line too.
196
                return bytes
197
            newline_pos = bytes.find('\n')
198
        line = bytes[:newline_pos+1]
199
        self._push_back(bytes[newline_pos+1:])
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
200
        return line
3236.3.2 by Andrew Bennetts
Fix SmartServerPipeStreamMedium._get_line too.
201
 
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
202
203
class SmartServerSocketStreamMedium(SmartServerStreamMedium):
204
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.
205
    def __init__(self, sock, backing_transport, root_client_path='/'):
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
206
        """Constructor.
207
208
        :param sock: the socket the server will read from.  It will be put
209
            into blocking mode.
210
        """
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.
211
        SmartServerStreamMedium.__init__(
212
            self, backing_transport, root_client_path=root_client_path)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
213
        sock.setblocking(True)
214
        self.socket = sock
215
216
    def _serve_one_request_unguarded(self, protocol):
217
        while protocol.next_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.
218
            bytes = self._get_bytes(4096)
219
            if bytes == '':
220
                self.finished = True
221
                return
222
            protocol.accept_bytes(bytes)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
223
        
3245.4.21 by Andrew Bennetts
Remove 'excess_buffer' attribute and another crufty comment.
224
        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.
225
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
226
    def _get_bytes(self, desired_count):
3236.3.5 by Andrew Bennetts
Add _get_push_back_buffer helper.
227
        if self._push_back_buffer is not None:
228
            return self._get_push_back_buffer()
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
229
        # We ignore the desired_count because on sockets it's more efficient to
230
        # read 4k at a time.
231
        return self.socket.recv(4096)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
232
    
233
    def terminate_due_to_error(self):
234
        self.socket.close()
235
        self.finished = True
236
237
    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.
238
        osutils.send_all(self.socket, bytes)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
239
240
241
class SmartServerPipeStreamMedium(SmartServerStreamMedium):
242
243
    def __init__(self, in_file, out_file, backing_transport):
244
        """Construct new server.
245
246
        :param in_file: Python file from which requests can be read.
247
        :param out_file: Python file to write responses.
248
        :param backing_transport: Transport for the directory served.
249
        """
250
        SmartServerStreamMedium.__init__(self, backing_transport)
2018.5.161 by Andrew Bennetts
Reinstate forcing binary mode on windows in SmartServerStreamMedium.
251
        if sys.platform == 'win32':
252
            # force binary mode for files
253
            import msvcrt
254
            for f in (in_file, out_file):
255
                fileno = getattr(f, 'fileno', None)
256
                if fileno:
257
                    msvcrt.setmode(fileno(), os.O_BINARY)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
258
        self._in = in_file
259
        self._out = out_file
260
261
    def _serve_one_request_unguarded(self, protocol):
262
        while True:
263
            bytes_to_read = protocol.next_read_size()
264
            if bytes_to_read == 0:
265
                # Finished serving this request.
266
                self._out.flush()
267
                return
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
268
            bytes = self._get_bytes(bytes_to_read)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
269
            if bytes == '':
270
                # Connection has been closed.
271
                self.finished = True
272
                self._out.flush()
273
                return
274
            protocol.accept_bytes(bytes)
275
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
276
    def _get_bytes(self, desired_count):
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.
277
        if self._push_back_buffer is not None:
3236.3.5 by Andrew Bennetts
Add _get_push_back_buffer helper.
278
            return self._get_push_back_buffer()
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
279
        return self._in.read(desired_count)
280
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
281
    def terminate_due_to_error(self):
282
        # TODO: This should log to a server log file, but no such thing
283
        # exists yet.  Andrew Bennetts 2006-09-29.
284
        self._out.close()
285
        self.finished = True
286
287
    def _write_out(self, bytes):
288
        self._out.write(bytes)
289
290
291
class SmartClientMediumRequest(object):
292
    """A request on a SmartClientMedium.
293
294
    Each request allows bytes to be provided to it via accept_bytes, and then
295
    the response bytes to be read via read_bytes.
296
297
    For instance:
298
    request.accept_bytes('123')
299
    request.finished_writing()
300
    result = request.read_bytes(3)
301
    request.finished_reading()
302
303
    It is up to the individual SmartClientMedium whether multiple concurrent
304
    requests can exist. See SmartClientMedium.get_request to obtain instances 
305
    of SmartClientMediumRequest, and the concrete Medium you are using for 
306
    details on concurrency and pipelining.
307
    """
308
309
    def __init__(self, medium):
310
        """Construct a SmartClientMediumRequest for the medium medium."""
311
        self._medium = medium
312
        # we track state by constants - we may want to use the same
313
        # pattern as BodyReader if it gets more complex.
314
        # valid states are: "writing", "reading", "done"
315
        self._state = "writing"
316
317
    def accept_bytes(self, bytes):
318
        """Accept bytes for inclusion in this request.
319
320
        This method may not be be called after finished_writing() has been
321
        called.  It depends upon the Medium whether or not the bytes will be
322
        immediately transmitted. Message based Mediums will tend to buffer the
323
        bytes until finished_writing() is called.
324
325
        :param bytes: A bytestring.
326
        """
327
        if self._state != "writing":
328
            raise errors.WritingCompleted(self)
329
        self._accept_bytes(bytes)
330
331
    def _accept_bytes(self, bytes):
332
        """Helper for accept_bytes.
333
334
        Accept_bytes checks the state of the request to determing if bytes
335
        should be accepted. After that it hands off to _accept_bytes to do the
336
        actual acceptance.
337
        """
338
        raise NotImplementedError(self._accept_bytes)
339
340
    def finished_reading(self):
341
        """Inform the request that all desired data has been read.
342
343
        This will remove the request from the pipeline for its medium (if the
344
        medium supports pipelining) and any further calls to methods on the
345
        request will raise ReadingCompleted.
346
        """
347
        if self._state == "writing":
348
            raise errors.WritingNotComplete(self)
349
        if self._state != "reading":
350
            raise errors.ReadingCompleted(self)
351
        self._state = "done"
352
        self._finished_reading()
353
354
    def _finished_reading(self):
355
        """Helper for finished_reading.
356
357
        finished_reading checks the state of the request to determine if 
358
        finished_reading is allowed, and if it is hands off to _finished_reading
359
        to perform the action.
360
        """
361
        raise NotImplementedError(self._finished_reading)
362
363
    def finished_writing(self):
364
        """Finish the writing phase of this request.
365
366
        This will flush all pending data for this request along the medium.
367
        After calling finished_writing, you may not call accept_bytes anymore.
368
        """
369
        if self._state != "writing":
370
            raise errors.WritingCompleted(self)
371
        self._state = "reading"
372
        self._finished_writing()
373
374
    def _finished_writing(self):
375
        """Helper for finished_writing.
376
377
        finished_writing checks the state of the request to determine if 
378
        finished_writing is allowed, and if it is hands off to _finished_writing
379
        to perform the action.
380
        """
381
        raise NotImplementedError(self._finished_writing)
382
383
    def read_bytes(self, count):
384
        """Read bytes from this requests response.
385
386
        This method will block and wait for count bytes to be read. It may not
387
        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.
388
        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.
389
        based mediums like HTTP.
390
        """
391
        if self._state == "writing":
392
            raise errors.WritingNotComplete(self)
393
        if self._state != "reading":
394
            raise errors.ReadingCompleted(self)
395
        return self._read_bytes(count)
396
397
    def _read_bytes(self, count):
398
        """Helper for read_bytes.
399
400
        read_bytes checks the state of the request to determing if bytes
401
        should be read. After that it hands off to _read_bytes to do the
402
        actual read.
403
        """
404
        raise NotImplementedError(self._read_bytes)
405
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
406
    def read_line(self):
407
        """Read bytes from this request's response until a newline byte.
408
        
409
        This isn't particularly efficient, so should only be used when the
410
        expected size of the line is quite short.
411
412
        :returns: a string of bytes ending in a newline (byte 0x0A).
413
        """
414
        # XXX: this duplicates SmartClientRequestProtocolOne._recv_tuple
415
        line = ''
416
        while not line or line[-1] != '\n':
417
            new_char = self.read_bytes(1)
418
            line += new_char
419
            if new_char == '':
3195.2.1 by Andrew Bennetts
Improve test coverage, and fix a bug revealed by the improved coverage.
420
                # end of file encountered reading from server
421
                raise errors.ConnectionReset(
422
                    "please check connectivity and permissions",
423
                    "(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.
424
        return line
425
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
426
427
class SmartClientMedium(object):
428
    """Smart client is a medium for sending smart protocol requests over."""
429
3241.1.1 by Andrew Bennetts
Shift protocol version querying from RemoteBzrDirFormat into SmartClientMedium.
430
    def __init__(self):
431
        super(SmartClientMedium, self).__init__()
3241.1.4 by Andrew Bennetts
Use get_smart_medium as suggested by Robert, and deal with the fallout.
432
        self._protocol_version_error = None
3241.1.1 by Andrew Bennetts
Shift protocol version querying from RemoteBzrDirFormat into SmartClientMedium.
433
        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).
434
        self._done_hello = False
3241.1.1 by Andrew Bennetts
Shift protocol version querying from RemoteBzrDirFormat into SmartClientMedium.
435
436
    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).
437
        """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.
438
        if self._protocol_version_error is not None:
439
            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).
440
        if not self._done_hello:
3241.1.4 by Andrew Bennetts
Use get_smart_medium as suggested by Robert, and deal with the fallout.
441
            try:
442
                medium_request = self.get_request()
443
                # Send a 'hello' request in protocol version one, for maximum
444
                # backwards compatibility.
445
                client_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).
446
                client_protocol.query_version()
447
                self._done_hello = True
3241.1.4 by Andrew Bennetts
Use get_smart_medium as suggested by Robert, and deal with the fallout.
448
            except errors.SmartProtocolError, e:
449
                # Cache the error, just like we would cache a successful
450
                # result.
451
                self._protocol_version_error = e
452
                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).
453
        return '2'
454
455
    def should_probe(self):
456
        """Should RemoteBzrDirFormat.probe_transport send a smart request on
457
        this medium?
458
459
        Some transports are unambiguously smart-only; there's no need to check
460
        if the transport is able to carry smart requests, because that's all
461
        it is for.  In those cases, this method should return False.
462
463
        But some HTTP transports can sometimes fail to carry smart requests,
464
        but still be usuable for accessing remote bzrdirs via plain file
465
        accesses.  So for those transports, their media should return True here
466
        so that RemoteBzrDirFormat can determine if it is appropriate for that
467
        transport.
468
        """
469
        return False
3241.1.1 by Andrew Bennetts
Shift protocol version querying from RemoteBzrDirFormat into SmartClientMedium.
470
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
471
    def disconnect(self):
472
        """If this medium maintains a persistent connection, close it.
473
        
474
        The default implementation does nothing.
475
        """
476
        
477
478
class SmartClientStreamMedium(SmartClientMedium):
479
    """Stream based medium common class.
480
481
    SmartClientStreamMediums operate on a stream. All subclasses use a common
482
    SmartClientStreamMediumRequest for their requests, and should implement
483
    _accept_bytes and _read_bytes to allow the request objects to send and
484
    receive bytes.
485
    """
486
487
    def __init__(self):
3241.1.1 by Andrew Bennetts
Shift protocol version querying from RemoteBzrDirFormat into SmartClientMedium.
488
        SmartClientMedium.__init__(self)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
489
        self._current_request = None
3213.1.1 by Andrew Bennetts
Recover (by reconnecting) if the server turns out not to understand the new requests in 1.2 that send bodies.
490
        # Be optimistic: we assume the remote end can accept new remote
491
        # requests until we get an error saying otherwise.  (1.2 adds some
492
        # requests that send bodies, which confuses older servers.)
493
        self._remote_is_at_least_1_2 = True
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
494
495
    def accept_bytes(self, bytes):
496
        self._accept_bytes(bytes)
497
498
    def __del__(self):
499
        """The SmartClientStreamMedium knows how to close the stream when it is
500
        finished with it.
501
        """
502
        self.disconnect()
503
504
    def _flush(self):
505
        """Flush the output stream.
506
        
507
        This method is used by the SmartClientStreamMediumRequest to ensure that
508
        all data for a request is sent, to avoid long timeouts or deadlocks.
509
        """
510
        raise NotImplementedError(self._flush)
511
512
    def get_request(self):
513
        """See SmartClientMedium.get_request().
514
515
        SmartClientStreamMedium always returns a SmartClientStreamMediumRequest
516
        for get_request.
517
        """
518
        return SmartClientStreamMediumRequest(self)
519
520
    def read_bytes(self, count):
521
        return self._read_bytes(count)
522
523
524
class SmartSimplePipesClientMedium(SmartClientStreamMedium):
525
    """A client medium using simple pipes.
526
    
527
    This client does not manage the pipes: it assumes they will always be open.
528
    """
529
530
    def __init__(self, readable_pipe, writeable_pipe):
531
        SmartClientStreamMedium.__init__(self)
532
        self._readable_pipe = readable_pipe
533
        self._writeable_pipe = writeable_pipe
534
535
    def _accept_bytes(self, bytes):
536
        """See SmartClientStreamMedium.accept_bytes."""
537
        self._writeable_pipe.write(bytes)
538
539
    def _flush(self):
540
        """See SmartClientStreamMedium._flush()."""
541
        self._writeable_pipe.flush()
542
543
    def _read_bytes(self, count):
544
        """See SmartClientStreamMedium._read_bytes."""
545
        return self._readable_pipe.read(count)
546
547
548
class SmartSSHClientMedium(SmartClientStreamMedium):
549
    """A client medium using SSH."""
550
    
551
    def __init__(self, host, port=None, username=None, password=None,
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
552
            vendor=None, bzr_remote_path=None):
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
553
        """Creates a client that will connect on the first use.
554
        
555
        :param vendor: An optional override for the ssh vendor to use. See
556
            bzrlib.transport.ssh for details on ssh vendors.
557
        """
558
        SmartClientStreamMedium.__init__(self)
559
        self._connected = False
560
        self._host = host
561
        self._password = password
562
        self._port = port
563
        self._username = username
564
        self._read_from = None
565
        self._ssh_connection = None
566
        self._vendor = vendor
567
        self._write_to = None
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
568
        self._bzr_remote_path = bzr_remote_path
569
        if self._bzr_remote_path is None:
570
            symbol_versioning.warn(
571
                'bzr_remote_path is required as of bzr 0.92',
572
                DeprecationWarning, stacklevel=2)
573
            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.
574
575
    def _accept_bytes(self, bytes):
576
        """See SmartClientStreamMedium.accept_bytes."""
577
        self._ensure_connection()
578
        self._write_to.write(bytes)
579
580
    def disconnect(self):
581
        """See SmartClientMedium.disconnect()."""
582
        if not self._connected:
583
            return
584
        self._read_from.close()
585
        self._write_to.close()
586
        self._ssh_connection.close()
587
        self._connected = False
588
589
    def _ensure_connection(self):
590
        """Connect this medium if not already connected."""
591
        if self._connected:
592
            return
593
        if self._vendor is None:
594
            vendor = ssh._get_ssh_vendor()
595
        else:
596
            vendor = self._vendor
597
        self._ssh_connection = vendor.connect_ssh(self._username,
598
                self._password, self._host, self._port,
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
599
                command=[self._bzr_remote_path, 'serve', '--inet',
600
                         '--directory=/', '--allow-writes'])
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
601
        self._read_from, self._write_to = \
602
            self._ssh_connection.get_filelike_channels()
603
        self._connected = True
604
605
    def _flush(self):
606
        """See SmartClientStreamMedium._flush()."""
607
        self._write_to.flush()
608
609
    def _read_bytes(self, count):
610
        """See SmartClientStreamMedium.read_bytes."""
611
        if not self._connected:
612
            raise errors.MediumNotConnected(self)
613
        return self._read_from.read(count)
614
615
3004.2.1 by Vincent Ladeuil
Fix 150860 by leaving port as user specified it.
616
# Port 4155 is the default port for bzr://, registered with IANA.
617
BZR_DEFAULT_INTERFACE = '0.0.0.0'
618
BZR_DEFAULT_PORT = 4155
619
620
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
621
class SmartTCPClientMedium(SmartClientStreamMedium):
622
    """A client medium using TCP."""
623
    
624
    def __init__(self, host, port):
625
        """Creates a client that will connect on the first use."""
626
        SmartClientStreamMedium.__init__(self)
627
        self._connected = False
628
        self._host = host
629
        self._port = port
630
        self._socket = None
631
632
    def _accept_bytes(self, bytes):
633
        """See SmartClientMedium.accept_bytes."""
634
        self._ensure_connection()
3118.2.1 by Andrew Bennetts
(andrew) Fix #115781 by passing no more than 64k at a time to socket.sendall.
635
        osutils.send_all(self._socket, bytes)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
636
637
    def disconnect(self):
638
        """See SmartClientMedium.disconnect()."""
639
        if not self._connected:
640
            return
641
        self._socket.close()
642
        self._socket = None
643
        self._connected = False
644
645
    def _ensure_connection(self):
646
        """Connect this medium if not already connected."""
647
        if self._connected:
648
            return
649
        self._socket = socket.socket()
650
        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.
651
        if self._port is None:
652
            port = BZR_DEFAULT_PORT
653
        else:
654
            port = int(self._port)
3180.1.1 by Andrew Bennetts
Don't traceback on host name errors when connecting to bzr://...
655
        try:
656
            self._socket.connect((self._host, port))
657
        except socket.error, err:
658
            # socket errors either have a (string) or (errno, string) as their
659
            # args.
660
            if type(err.args) is str:
661
                err_msg = err.args
662
            else:
663
                err_msg = err.args[1]
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
664
            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://...
665
                    (self._host, port, err_msg))
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
666
        self._connected = True
667
668
    def _flush(self):
669
        """See SmartClientStreamMedium._flush().
670
        
671
        For TCP we do no flushing. We may want to turn off TCP_NODELAY and 
672
        add a means to do a flush, but that can be done in the future.
673
        """
674
675
    def _read_bytes(self, count):
676
        """See SmartClientMedium.read_bytes."""
677
        if not self._connected:
678
            raise errors.MediumNotConnected(self)
679
        return self._socket.recv(count)
680
681
682
class SmartClientStreamMediumRequest(SmartClientMediumRequest):
683
    """A SmartClientMediumRequest that works with an SmartClientStreamMedium."""
684
685
    def __init__(self, medium):
686
        SmartClientMediumRequest.__init__(self, medium)
687
        # check that we are safe concurrency wise. If some streams start
688
        # allowing concurrent requests - i.e. via multiplexing - then this
689
        # assert should be moved to SmartClientStreamMedium.get_request,
690
        # and the setting/unsetting of _current_request likewise moved into
691
        # that class : but its unneeded overhead for now. RBC 20060922
692
        if self._medium._current_request is not None:
693
            raise errors.TooManyConcurrentRequests(self._medium)
694
        self._medium._current_request = self
695
696
    def _accept_bytes(self, bytes):
697
        """See SmartClientMediumRequest._accept_bytes.
698
        
699
        This forwards to self._medium._accept_bytes because we are operating
700
        on the mediums stream.
701
        """
702
        self._medium._accept_bytes(bytes)
703
704
    def _finished_reading(self):
705
        """See SmartClientMediumRequest._finished_reading.
706
707
        This clears the _current_request on self._medium to allow a new 
708
        request to be created.
709
        """
710
        assert self._medium._current_request is self
711
        self._medium._current_request = None
712
        
713
    def _finished_writing(self):
714
        """See SmartClientMediumRequest._finished_writing.
715
716
        This invokes self._medium._flush to ensure all bytes are transmitted.
717
        """
718
        self._medium._flush()
719
720
    def _read_bytes(self, count):
721
        """See SmartClientMediumRequest._read_bytes.
722
        
723
        This forwards to self._medium._read_bytes because we are operating
724
        on the mediums stream.
725
        """
726
        return self._medium._read_bytes(count)
3245.4.32 by Andrew Bennetts
Undo trivial whitespace change relative to bzr.dev.
727