/brz/remove-bazaar

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