~bzr-pqm/bzr/bzr.dev

5752.3.8 by John Arbash Meinel
Merge bzr.dev 5764 to resolve release-notes (aka NEWS) conflicts
1
# Copyright (C) 2006-2011 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
6133.4.10 by John Arbash Meinel
Handle the win32 not-a-socket errors. I think this is ~ready. At least for feedback.
27
import errno
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
28
import os
2018.5.162 by Andrew Bennetts
Add some missing _ensure_real calls, and a missing import.
29
import sys
6133.4.8 by John Arbash Meinel
Refactor a bit. Use a common _wait_for_descriptor code.
30
import time
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
5222.2.9 by Robert Collins
Write up some doc about bzrlib.initialize.
33
import bzrlib
3530.1.1 by John Arbash Meinel
Make bzrlib.smart use lazy imports.
34
from bzrlib.lazy_import import lazy_import
35
lazy_import(globals(), """
6133.4.7 by John Arbash Meinel
Currently causes 5-10 failures in bt.per_branch.test_branch Remote out of 150 tests.
36
import select
5011.3.11 by Andrew Bennetts
Consolidate changes, try to minimise unnecessary changes and tidy up those that kept.
37
import socket
4913.1.1 by John Arbash Meinel
Switch to using thread.get_ident() which is available on all python versions.
38
import thread
3731.2.4 by Andrew Bennetts
Minor tweaks.
39
import weakref
4889.2.2 by John Arbash Meinel
Add a -Dhpssthread debug flag to include thread.ident info.
40
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
41
from bzrlib import (
3731.2.1 by Andrew Bennetts
Show total HPSS calls (if any) on stderr when -Dhpss is active.
42
    debug,
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
43
    errors,
3731.2.5 by Andrew Bennetts
Rework hpss call counter.
44
    trace,
3958.1.1 by Andrew Bennetts
Report traffic on smart media as transport activity.
45
    ui,
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
46
    urlutils,
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
47
    )
6138.3.4 by Jonathan Riddell
add gettext() to uses of trace.note()
48
from bzrlib.i18n import gettext
6133.4.61 by John Arbash Meinel
Expose infrastructure so that we can test the Inet portion of the server.
49
from bzrlib.smart import client, protocol, request, signals, vfs
3066.2.1 by John Arbash Meinel
We don't require paramiko for bzr+ssh.
50
from bzrlib.transport import ssh
3530.1.1 by John Arbash Meinel
Make bzrlib.smart use lazy imports.
51
""")
6133.4.55 by John Arbash Meinel
Now we've implemented the basic structure.
52
from bzrlib import osutils
2018.5.17 by Andrew Bennetts
Paramaterise the commands handled by SmartServerRequestHandler.
53
5011.3.3 by Martin
Reintroduce EINTR handling only for socket object functions and general cleanup
54
# Throughout this module buffer size parameters are either limited to be at
5011.3.11 by Andrew Bennetts
Consolidate changes, try to minimise unnecessary changes and tidy up those that kept.
55
# most _MAX_READ_SIZE, or are ignored and _MAX_READ_SIZE is used instead.
56
# For this module's purposes, MAX_SOCKET_CHUNK is a reasonable size for reads
57
# from non-sockets as well.
58
_MAX_READ_SIZE = osutils.MAX_SOCKET_CHUNK
3565.1.3 by Andrew Bennetts
Define a _MAX_READ_SIZE constant as suggested by John's review.
59
3245.4.16 by Andrew Bennetts
Remove duplication of request version identification logic in wsgi.py
60
def _get_protocol_factory_for_bytes(bytes):
61
    """Determine the right protocol factory for 'bytes'.
62
63
    This will return an appropriate protocol factory depending on the version
64
    of the protocol being used, as determined by inspecting the given bytes.
65
    The bytes should have at least one newline byte (i.e. be a whole line),
66
    otherwise it's possible that a request will be incorrectly identified as
67
    version 1.
68
69
    Typical use would be::
70
71
         factory, unused_bytes = _get_protocol_factory_for_bytes(bytes)
72
         server_protocol = factory(transport, write_func, root_client_path)
73
         server_protocol.accept_bytes(unused_bytes)
74
75
    :param bytes: a str of bytes of the start of the request.
76
    :returns: 2-tuple of (protocol_factory, unused_bytes).  protocol_factory is
77
        a callable that takes three args: transport, write_func,
78
        root_client_path.  unused_bytes are any bytes that were not part of a
79
        protocol version marker.
80
    """
3530.1.1 by John Arbash Meinel
Make bzrlib.smart use lazy imports.
81
    if bytes.startswith(protocol.MESSAGE_VERSION_THREE):
82
        protocol_factory = protocol.build_server_protocol_three
83
        bytes = bytes[len(protocol.MESSAGE_VERSION_THREE):]
84
    elif bytes.startswith(protocol.REQUEST_VERSION_TWO):
85
        protocol_factory = protocol.SmartServerRequestProtocolTwo
86
        bytes = bytes[len(protocol.REQUEST_VERSION_TWO):]
3245.4.16 by Andrew Bennetts
Remove duplication of request version identification logic in wsgi.py
87
    else:
3530.1.1 by John Arbash Meinel
Make bzrlib.smart use lazy imports.
88
        protocol_factory = protocol.SmartServerRequestProtocolOne
3245.4.16 by Andrew Bennetts
Remove duplication of request version identification logic in wsgi.py
89
    return protocol_factory, bytes
90
91
3606.4.1 by Andrew Bennetts
Fix NotImplementedError when probing for smart protocol via HTTP.
92
def _get_line(read_bytes_func):
93
    """Read bytes using read_bytes_func until a newline byte.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
94
3606.4.1 by Andrew Bennetts
Fix NotImplementedError when probing for smart protocol via HTTP.
95
    This isn't particularly efficient, so should only be used when the
96
    expected size of the line is quite short.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
97
3606.4.1 by Andrew Bennetts
Fix NotImplementedError when probing for smart protocol via HTTP.
98
    :returns: a tuple of two strs: (line, excess)
99
    """
100
    newline_pos = -1
101
    bytes = ''
102
    while newline_pos == -1:
103
        new_bytes = read_bytes_func(1)
104
        bytes += new_bytes
105
        if new_bytes == '':
106
            # Ran out of bytes before receiving a complete line.
107
            return bytes, ''
108
        newline_pos = bytes.find('\n')
109
    line = bytes[:newline_pos+1]
110
    excess = bytes[newline_pos+1:]
111
    return line, excess
112
113
3565.1.1 by Andrew Bennetts
Read no more then 64k at a time in the smart protocol code.
114
class SmartMedium(object):
115
    """Base class for smart protocol media, both client- and server-side."""
116
117
    def __init__(self):
118
        self._push_back_buffer = None
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
119
3565.1.1 by Andrew Bennetts
Read no more then 64k at a time in the smart protocol code.
120
    def _push_back(self, bytes):
121
        """Return unused bytes to the medium, because they belong to the next
122
        request(s).
123
124
        This sets the _push_back_buffer to the given bytes.
125
        """
126
        if self._push_back_buffer is not None:
127
            raise AssertionError(
128
                "_push_back called when self._push_back_buffer is %r"
129
                % (self._push_back_buffer,))
130
        if bytes == '':
131
            return
132
        self._push_back_buffer = bytes
133
134
    def _get_push_back_buffer(self):
135
        if self._push_back_buffer == '':
136
            raise AssertionError(
137
                '%s._push_back_buffer should never be the empty string, '
138
                'which can be confused with EOF' % (self,))
139
        bytes = self._push_back_buffer
140
        self._push_back_buffer = None
141
        return bytes
142
143
    def read_bytes(self, desired_count):
3565.1.2 by Andrew Bennetts
Delete some more code, fix some bugs, add more comments.
144
        """Read some bytes from this medium.
145
146
        :returns: some bytes, possibly more or less than the number requested
147
            in 'desired_count' depending on the medium.
148
        """
149
        if self._push_back_buffer is not None:
150
            return self._get_push_back_buffer()
3565.1.3 by Andrew Bennetts
Define a _MAX_READ_SIZE constant as suggested by John's review.
151
        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.
152
        return self._read_bytes(bytes_to_read)
153
154
    def _read_bytes(self, count):
155
        raise NotImplementedError(self._read_bytes)
156
157
    def _get_line(self):
158
        """Read bytes from this request's response until a newline byte.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
159
3565.1.1 by Andrew Bennetts
Read no more then 64k at a time in the smart protocol code.
160
        This isn't particularly efficient, so should only be used when the
161
        expected size of the line is quite short.
162
163
        :returns: a string of bytes ending in a newline (byte 0x0A).
164
        """
3606.4.1 by Andrew Bennetts
Fix NotImplementedError when probing for smart protocol via HTTP.
165
        line, excess = _get_line(self.read_bytes)
166
        self._push_back(excess)
3565.1.1 by Andrew Bennetts
Read no more then 64k at a time in the smart protocol code.
167
        return line
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
168
3958.1.1 by Andrew Bennetts
Report traffic on smart media as transport activity.
169
    def _report_activity(self, bytes, direction):
170
        """Notify that this medium has activity.
171
172
        Implementations should call this from all methods that actually do IO.
173
        Be careful that it's not called twice, if one method is implemented on
174
        top of another.
175
176
        :param bytes: Number of bytes read or written.
177
        :param direction: 'read' or 'write' or None.
178
        """
179
        ui.ui_factory.report_transport_activity(self, bytes, direction)
180
3565.1.1 by Andrew Bennetts
Read no more then 64k at a time in the smart protocol code.
181
6133.4.10 by John Arbash Meinel
Handle the win32 not-a-socket errors. I think this is ~ready. At least for feedback.
182
_bad_file_descriptor = (errno.EBADF,)
183
if sys.platform == 'win32':
184
    # Given on Windows if you pass a closed socket to select.select. Probably
185
    # also given if you pass a file handle to select.
186
    WSAENOTSOCK = 10038
187
    _bad_file_descriptor += (WSAENOTSOCK,)
188
189
3565.1.1 by Andrew Bennetts
Read no more then 64k at a time in the smart protocol code.
190
class SmartServerStreamMedium(SmartMedium):
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
191
    """Handles smart commands coming over a stream.
192
193
    The stream may be a pipe connected to sshd, or a tcp socket, or an
194
    in-process fifo for testing.
195
196
    One instance is created for each connected client; it can serve multiple
197
    requests in the lifetime of the connection.
198
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
199
    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.
200
    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.
201
202
    :ivar _push_back_buffer: a str of bytes that have been read from the stream
203
        but not used yet, or None if there are no buffered bytes.  Subclasses
204
        should make sure to exhaust this buffer before reading more bytes from
205
        the stream.  See also the _push_back method.
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
206
    """
207
6133.4.43 by John Arbash Meinel
Initial implementation of SIGHUP for bzr serve. bug #795025.
208
    _timer = time.time
209
6133.4.15 by John Arbash Meinel
Start working on exposing timeout as a configuration item.
210
    def __init__(self, backing_transport, root_client_path='/', timeout=None):
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
211
        """Construct new server.
212
213
        :param backing_transport: Transport for the directory served.
214
        """
215
        # backing_transport could be passed to serve instead of __init__
216
        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.
217
        self.root_client_path = root_client_path
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
218
        self.finished = False
6133.4.15 by John Arbash Meinel
Start working on exposing timeout as a configuration item.
219
        if timeout is None:
6133.4.26 by John Arbash Meinel
get rid of the default timeout parameters.
220
            raise AssertionError('You must supply a timeout.')
6133.4.15 by John Arbash Meinel
Start working on exposing timeout as a configuration item.
221
        self._client_timeout = timeout
222
        self._client_poll_timeout = min(timeout / 10.0, 1.0)
3565.1.1 by Andrew Bennetts
Read no more then 64k at a time in the smart protocol code.
223
        SmartMedium.__init__(self)
3236.3.5 by Andrew Bennetts
Add _get_push_back_buffer helper.
224
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
225
    def serve(self):
226
        """Serve requests until the client disconnects."""
227
        # Keep a reference to stderr because the sys module's globals get set to
228
        # None during interpreter shutdown.
229
        from sys import stderr
230
        try:
231
            while not self.finished:
2432.2.3 by Andrew Bennetts
Merge from bzr.dev.
232
                server_protocol = self._build_protocol()
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
233
                self._serve_one_request(server_protocol)
6133.4.11 by John Arbash Meinel
It turns out that if we don't explicitly close the socket, it hangs around somewhere.
234
        except errors.ConnectionTimeout, e:
235
            trace.note('%s' % (e,))
6133.4.12 by John Arbash Meinel
Don't traceback for timeouts, and give better documentation about why we don't just select.
236
            trace.log_exception_quietly()
6133.5.2 by John Arbash Meinel
Rename _close to _disconnect_client. This makes it more obvious.
237
            self._disconnect_client()
6133.4.12 by John Arbash Meinel
Don't traceback for timeouts, and give better documentation about why we don't just select.
238
            # We reported it, no reason to make a big fuss.
239
            return
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
240
        except Exception, e:
241
            stderr.write("%s terminating on exception %s\n" % (self, e))
242
            raise
6133.4.61 by John Arbash Meinel
Expose infrastructure so that we can test the Inet portion of the server.
243
        self._disconnect_client()
6133.4.43 by John Arbash Meinel
Initial implementation of SIGHUP for bzr serve. bug #795025.
244
6133.4.44 by John Arbash Meinel
Move the code into bzrlib.smart.signals.
245
    def _stop_gracefully(self):
246
        """When we finish this message, stop looking for more."""
247
        trace.mutter('Stopping %s' % (self,))
6133.4.43 by John Arbash Meinel
Initial implementation of SIGHUP for bzr serve. bug #795025.
248
        self.finished = True
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
249
6133.5.2 by John Arbash Meinel
Rename _close to _disconnect_client. This makes it more obvious.
250
    def _disconnect_client(self):
6133.4.11 by John Arbash Meinel
It turns out that if we don't explicitly close the socket, it hangs around somewhere.
251
        """Close the current connection. We stopped due to a timeout/etc."""
252
        # The default implementation is a no-op, because that is all we used to
253
        # do when disconnecting from a client. I suppose we never had the
254
        # *server* initiate a disconnect, before
255
256
    def _wait_for_bytes_with_timeout(self, timeout_seconds):
257
        """Wait for more bytes to be read, but timeout if none available.
258
259
        This allows us to detect idle connections, and stop trying to read from
260
        them, without setting the socket itself to non-blocking. This also
261
        allows us to specify when we watch for idle timeouts.
262
263
        :return: Did we timeout? (True if we timed out, False if there is data
264
            to be read)
265
        """
266
        raise NotImplementedError(self._wait_for_bytes_with_timeout)
267
2432.2.2 by Andrew Bennetts
Smart server mediums now detect which protocol version a request is and dispatch accordingly.
268
    def _build_protocol(self):
2432.2.8 by Andrew Bennetts
NEWS entry, greatly improved docstring in bzrlib.smart.
269
        """Identifies the version of the incoming request, and returns an
270
        a protocol object that can interpret it.
271
272
        If more bytes than the version prefix of the request are read, they will
273
        be fed into the protocol before it is returned.
274
275
        :returns: a SmartServerRequestProtocol.
276
        """
6133.4.42 by John Arbash Meinel
Change the code to just raise ConnectionTimeout.
277
        self._wait_for_bytes_with_timeout(self._client_timeout)
6133.4.43 by John Arbash Meinel
Initial implementation of SIGHUP for bzr serve. bug #795025.
278
        if self.finished:
279
            # We're stopping, so don't try to do any more work
280
            return None
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
281
        bytes = self._get_line()
3245.4.16 by Andrew Bennetts
Remove duplication of request version identification logic in wsgi.py
282
        protocol_factory, unused_bytes = _get_protocol_factory_for_bytes(bytes)
3245.4.14 by Andrew Bennetts
Merge from bzr.dev (via loom thread).
283
        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.
284
            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
285
        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.
286
        return protocol
287
6133.4.8 by John Arbash Meinel
Refactor a bit. Use a common _wait_for_descriptor code.
288
    def _wait_on_descriptor(self, fd, timeout_seconds):
6133.4.41 by John Arbash Meinel
Re-order the loop a bit. Move the exception handling into the loop, so that we can handle EINTR.
289
        """select() on a file descriptor, waiting for nonblocking read()
290
6133.4.42 by John Arbash Meinel
Change the code to just raise ConnectionTimeout.
291
        This will raise a ConnectionTimeout exception if we do not get a
292
        readable handle before timeout_seconds.
293
        :return: None
6133.4.41 by John Arbash Meinel
Re-order the loop a bit. Move the exception handling into the loop, so that we can handle EINTR.
294
        """
6133.4.43 by John Arbash Meinel
Initial implementation of SIGHUP for bzr serve. bug #795025.
295
        t_end = self._timer() + timeout_seconds
6133.4.41 by John Arbash Meinel
Re-order the loop a bit. Move the exception handling into the loop, so that we can handle EINTR.
296
        poll_timeout = min(timeout_seconds, self._client_poll_timeout)
297
        rs = xs = None
6133.4.43 by John Arbash Meinel
Initial implementation of SIGHUP for bzr serve. bug #795025.
298
        while not rs and not xs and self._timer() < t_end:
299
            if self.finished:
300
                return
6133.4.41 by John Arbash Meinel
Re-order the loop a bit. Move the exception handling into the loop, so that we can handle EINTR.
301
            try:
6133.4.39 by John Arbash Meinel
pass fd in the 'check for errors' section of select.
302
                rs, _, xs = select.select([fd], [], [fd], poll_timeout)
6133.4.41 by John Arbash Meinel
Re-order the loop a bit. Move the exception handling into the loop, so that we can handle EINTR.
303
            except (select.error, socket.error) as e:
304
                err = getattr(e, 'errno', None)
305
                if err is None and getattr(e, 'args', None) is not None:
306
                    # select.error doesn't have 'errno', it just has args[0]
6133.4.8 by John Arbash Meinel
Refactor a bit. Use a common _wait_for_descriptor code.
307
                    err = e.args[0]
6133.4.41 by John Arbash Meinel
Re-order the loop a bit. Move the exception handling into the loop, so that we can handle EINTR.
308
                if err in _bad_file_descriptor:
6133.4.42 by John Arbash Meinel
Change the code to just raise ConnectionTimeout.
309
                    return # Not a socket indicates read() will fail
6133.4.41 by John Arbash Meinel
Re-order the loop a bit. Move the exception handling into the loop, so that we can handle EINTR.
310
                elif err == errno.EINTR:
311
                    # Interrupted, keep looping.
312
                    continue
313
                raise
6133.4.40 by John Arbash Meinel
Treat an 'errfds' as just something we want to try and read from later.
314
        if rs or xs:
6133.4.42 by John Arbash Meinel
Change the code to just raise ConnectionTimeout.
315
            return
316
        raise errors.ConnectionTimeout('disconnecting client after %.1f seconds'
317
                                       % (timeout_seconds,))
6133.4.8 by John Arbash Meinel
Refactor a bit. Use a common _wait_for_descriptor code.
318
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
319
    def _serve_one_request(self, protocol):
320
        """Read one request from input, process, send back a response.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
321
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
322
        :param protocol: a SmartServerRequestProtocol.
323
        """
6175.1.5 by John Arbash Meinel
Suppress ConnectionTimeout as a server-side exception.
324
        if protocol is None:
325
            return
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
326
        try:
327
            self._serve_one_request_unguarded(protocol)
328
        except KeyboardInterrupt:
329
            raise
330
        except Exception, e:
331
            self.terminate_due_to_error()
332
333
    def terminate_due_to_error(self):
334
        """Called when an unhandled exception from the protocol occurs."""
335
        raise NotImplementedError(self.terminate_due_to_error)
336
3565.1.2 by Andrew Bennetts
Delete some more code, fix some bugs, add more comments.
337
    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.
338
        """Get some bytes from the medium.
339
340
        :param desired_count: number of bytes we want to read.
341
        """
3565.1.2 by Andrew Bennetts
Delete some more code, fix some bugs, add more comments.
342
        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.
343
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
344
345
class SmartServerSocketStreamMedium(SmartServerStreamMedium):
346
6133.4.15 by John Arbash Meinel
Start working on exposing timeout as a configuration item.
347
    def __init__(self, sock, backing_transport, root_client_path='/',
348
                 timeout=None):
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
349
        """Constructor.
350
351
        :param sock: the socket the server will read from.  It will be put
352
            into blocking mode.
353
        """
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.
354
        SmartServerStreamMedium.__init__(
6133.4.15 by John Arbash Meinel
Start working on exposing timeout as a configuration item.
355
            self, backing_transport, root_client_path=root_client_path,
356
            timeout=timeout)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
357
        sock.setblocking(True)
358
        self.socket = sock
6133.4.62 by John Arbash Meinel
Add a nicer repr for shutting down.
359
        # Get the getpeername now, as we might be closed later when we care.
360
        try:
361
            self._client_info = sock.getpeername()
362
        except socket.error:
363
            self._client_info = '<unknown>'
364
365
    def __str__(self):
366
        return '%s(client=%s)' % (self.__class__.__name__, self._client_info)
367
368
    def __repr__(self):
369
        return '%s.%s(client=%s)' % (self.__module__, self.__class__.__name__,
370
            self._client_info)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
371
372
    def _serve_one_request_unguarded(self, protocol):
373
        while protocol.next_read_size():
3565.1.3 by Andrew Bennetts
Define a _MAX_READ_SIZE constant as suggested by John's review.
374
            # We can safely try to read large chunks.  If there is less data
5011.3.11 by Andrew Bennetts
Consolidate changes, try to minimise unnecessary changes and tidy up those that kept.
375
            # than MAX_SOCKET_CHUNK ready, the socket will just return a
376
            # short read immediately rather than block.
377
            bytes = self.read_bytes(osutils.MAX_SOCKET_CHUNK)
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.
378
            if bytes == '':
379
                self.finished = True
380
                return
381
            protocol.accept_bytes(bytes)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
382
3245.4.21 by Andrew Bennetts
Remove 'excess_buffer' attribute and another crufty comment.
383
        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.
384
6133.5.2 by John Arbash Meinel
Rename _close to _disconnect_client. This makes it more obvious.
385
    def _disconnect_client(self):
6133.4.11 by John Arbash Meinel
It turns out that if we don't explicitly close the socket, it hangs around somewhere.
386
        """Close the current connection. We stopped due to a timeout/etc."""
387
        self.socket.close()
388
6133.4.1 by John Arbash Meinel
Add a _wait_for_bytes_with_timeout helper function.
389
    def _wait_for_bytes_with_timeout(self, timeout_seconds):
390
        """Wait for more bytes to be read, but timeout if none available.
391
392
        This allows us to detect idle connections, and stop trying to read from
393
        them, without setting the socket itself to non-blocking. This also
394
        allows us to specify when we watch for idle timeouts.
6133.4.2 by John Arbash Meinel
Implement waiting for Pipe mediums, including handling ones
395
6133.4.42 by John Arbash Meinel
Change the code to just raise ConnectionTimeout.
396
        :return: None, this will raise ConnectionTimeout if we time out before
397
            data is available.
6133.4.1 by John Arbash Meinel
Add a _wait_for_bytes_with_timeout helper function.
398
        """
6133.4.8 by John Arbash Meinel
Refactor a bit. Use a common _wait_for_descriptor code.
399
        return self._wait_on_descriptor(self.socket, timeout_seconds)
6133.4.1 by John Arbash Meinel
Add a _wait_for_bytes_with_timeout helper function.
400
3565.1.2 by Andrew Bennetts
Delete some more code, fix some bugs, add more comments.
401
    def _read_bytes(self, desired_count):
5011.3.11 by Andrew Bennetts
Consolidate changes, try to minimise unnecessary changes and tidy up those that kept.
402
        return osutils.read_bytes_from_socket(
403
            self.socket, self._report_activity)
3565.1.1 by Andrew Bennetts
Read no more then 64k at a time in the smart protocol code.
404
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
405
    def terminate_due_to_error(self):
3245.4.59 by Andrew Bennetts
Various tweaks in response to Martin's review.
406
        # TODO: This should log to a server log file, but no such thing
407
        # exists yet.  Andrew Bennetts 2006-09-29.
5011.3.1 by Martin
Revert second-phase EINTR changes
408
        self.socket.close()
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
409
        self.finished = True
410
411
    def _write_out(self, bytes):
4889.2.1 by John Arbash Meinel
Make -Dhpss log debug information for the server process.
412
        tstart = osutils.timer_func()
5011.3.9 by Andrew Bennetts
Remove _send_bytes_chunked.
413
        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.
414
        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.
415
            thread_id = thread.get_ident()
4889.2.3 by John Arbash Meinel
Get rid of -Dhpssthread, just always include it.
416
            trace.mutter('%12s: [%s] %d bytes to the socket in %.3fs'
417
                         % ('wrote', thread_id, len(bytes),
4889.2.2 by John Arbash Meinel
Add a -Dhpssthread debug flag to include thread.ident info.
418
                            osutils.timer_func() - tstart))
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
419
420
421
class SmartServerPipeStreamMedium(SmartServerStreamMedium):
422
6133.4.15 by John Arbash Meinel
Start working on exposing timeout as a configuration item.
423
    def __init__(self, in_file, out_file, backing_transport, timeout=None):
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
424
        """Construct new server.
425
426
        :param in_file: Python file from which requests can be read.
427
        :param out_file: Python file to write responses.
428
        :param backing_transport: Transport for the directory served.
429
        """
6133.4.15 by John Arbash Meinel
Start working on exposing timeout as a configuration item.
430
        SmartServerStreamMedium.__init__(self, backing_transport,
431
            timeout=timeout)
2018.5.161 by Andrew Bennetts
Reinstate forcing binary mode on windows in SmartServerStreamMedium.
432
        if sys.platform == 'win32':
433
            # force binary mode for files
434
            import msvcrt
435
            for f in (in_file, out_file):
436
                fileno = getattr(f, 'fileno', None)
437
                if fileno:
438
                    msvcrt.setmode(fileno(), os.O_BINARY)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
439
        self._in = in_file
440
        self._out = out_file
441
6133.4.61 by John Arbash Meinel
Expose infrastructure so that we can test the Inet portion of the server.
442
    def serve(self):
443
        """See SmartServerStreamMedium.serve"""
444
        # This is the regular serve, except it adds signal trapping for soft
445
        # shutdown.
446
        stop_gracefully = self._stop_gracefully
447
        signals.register_on_hangup(id(self), stop_gracefully)
448
        try:
449
            return super(SmartServerPipeStreamMedium, self).serve()
450
        finally:
451
            signals.unregister_on_hangup(id(self))
452
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
453
    def _serve_one_request_unguarded(self, protocol):
454
        while True:
3565.1.2 by Andrew Bennetts
Delete some more code, fix some bugs, add more comments.
455
            # We need to be careful not to read past the end of the current
456
            # request, or else the read from the pipe will block, so we use
457
            # protocol.next_read_size().
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
458
            bytes_to_read = protocol.next_read_size()
459
            if bytes_to_read == 0:
460
                # Finished serving this request.
5011.3.1 by Martin
Revert second-phase EINTR changes
461
                self._out.flush()
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
462
                return
3565.1.2 by Andrew Bennetts
Delete some more code, fix some bugs, add more comments.
463
            bytes = self.read_bytes(bytes_to_read)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
464
            if bytes == '':
465
                # Connection has been closed.
466
                self.finished = True
5011.3.1 by Martin
Revert second-phase EINTR changes
467
                self._out.flush()
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
468
                return
469
            protocol.accept_bytes(bytes)
470
6133.5.2 by John Arbash Meinel
Rename _close to _disconnect_client. This makes it more obvious.
471
    def _disconnect_client(self):
6133.4.11 by John Arbash Meinel
It turns out that if we don't explicitly close the socket, it hangs around somewhere.
472
        self._in.close()
6133.4.63 by John Arbash Meinel
Flush before we close _out.
473
        self._out.flush()
6133.4.11 by John Arbash Meinel
It turns out that if we don't explicitly close the socket, it hangs around somewhere.
474
        self._out.close()
475
6133.4.2 by John Arbash Meinel
Implement waiting for Pipe mediums, including handling ones
476
    def _wait_for_bytes_with_timeout(self, timeout_seconds):
477
        """Wait for more bytes to be read, but timeout if none available.
478
479
        This allows us to detect idle connections, and stop trying to read from
480
        them, without setting the socket itself to non-blocking. This also
481
        allows us to specify when we watch for idle timeouts.
482
6133.4.42 by John Arbash Meinel
Change the code to just raise ConnectionTimeout.
483
        :return: None, this will raise ConnectionTimeout if we time out before
484
            data is available.
6133.4.2 by John Arbash Meinel
Implement waiting for Pipe mediums, including handling ones
485
        """
6133.4.10 by John Arbash Meinel
Handle the win32 not-a-socket errors. I think this is ~ready. At least for feedback.
486
        if (getattr(self._in, 'fileno', None) is None
487
            or sys.platform == 'win32'):
488
            # You can't select() file descriptors on Windows.
6133.4.42 by John Arbash Meinel
Change the code to just raise ConnectionTimeout.
489
            return
6133.4.8 by John Arbash Meinel
Refactor a bit. Use a common _wait_for_descriptor code.
490
        return self._wait_on_descriptor(self._in, timeout_seconds)
6133.4.2 by John Arbash Meinel
Implement waiting for Pipe mediums, including handling ones
491
3565.1.2 by Andrew Bennetts
Delete some more code, fix some bugs, add more comments.
492
    def _read_bytes(self, desired_count):
5011.3.1 by Martin
Revert second-phase EINTR changes
493
        return 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.
494
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
495
    def terminate_due_to_error(self):
496
        # TODO: This should log to a server log file, but no such thing
497
        # exists yet.  Andrew Bennetts 2006-09-29.
5011.3.1 by Martin
Revert second-phase EINTR changes
498
        self._out.close()
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
499
        self.finished = True
500
501
    def _write_out(self, bytes):
5011.3.1 by Martin
Revert second-phase EINTR changes
502
        self._out.write(bytes)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
503
504
3565.1.2 by Andrew Bennetts
Delete some more code, fix some bugs, add more comments.
505
class SmartClientMediumRequest(object):
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
506
    """A request on a SmartClientMedium.
507
508
    Each request allows bytes to be provided to it via accept_bytes, and then
509
    the response bytes to be read via read_bytes.
510
511
    For instance:
512
    request.accept_bytes('123')
513
    request.finished_writing()
514
    result = request.read_bytes(3)
515
    request.finished_reading()
516
517
    It is up to the individual SmartClientMedium whether multiple concurrent
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
518
    requests can exist. See SmartClientMedium.get_request to obtain instances
519
    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.
520
    details on concurrency and pipelining.
521
    """
522
523
    def __init__(self, medium):
524
        """Construct a SmartClientMediumRequest for the medium medium."""
525
        self._medium = medium
526
        # we track state by constants - we may want to use the same
527
        # pattern as BodyReader if it gets more complex.
528
        # valid states are: "writing", "reading", "done"
529
        self._state = "writing"
530
531
    def accept_bytes(self, bytes):
532
        """Accept bytes for inclusion in this request.
533
4031.3.1 by Frank Aspell
Fixing various typos
534
        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.
535
        called.  It depends upon the Medium whether or not the bytes will be
536
        immediately transmitted. Message based Mediums will tend to buffer the
537
        bytes until finished_writing() is called.
538
539
        :param bytes: A bytestring.
540
        """
541
        if self._state != "writing":
542
            raise errors.WritingCompleted(self)
543
        self._accept_bytes(bytes)
544
545
    def _accept_bytes(self, bytes):
546
        """Helper for accept_bytes.
547
548
        Accept_bytes checks the state of the request to determing if bytes
549
        should be accepted. After that it hands off to _accept_bytes to do the
550
        actual acceptance.
551
        """
552
        raise NotImplementedError(self._accept_bytes)
553
554
    def finished_reading(self):
555
        """Inform the request that all desired data has been read.
556
557
        This will remove the request from the pipeline for its medium (if the
558
        medium supports pipelining) and any further calls to methods on the
559
        request will raise ReadingCompleted.
560
        """
561
        if self._state == "writing":
562
            raise errors.WritingNotComplete(self)
563
        if self._state != "reading":
564
            raise errors.ReadingCompleted(self)
565
        self._state = "done"
566
        self._finished_reading()
567
568
    def _finished_reading(self):
569
        """Helper for finished_reading.
570
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
571
        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.
572
        finished_reading is allowed, and if it is hands off to _finished_reading
573
        to perform the action.
574
        """
575
        raise NotImplementedError(self._finished_reading)
576
577
    def finished_writing(self):
578
        """Finish the writing phase of this request.
579
580
        This will flush all pending data for this request along the medium.
581
        After calling finished_writing, you may not call accept_bytes anymore.
582
        """
583
        if self._state != "writing":
584
            raise errors.WritingCompleted(self)
585
        self._state = "reading"
586
        self._finished_writing()
587
588
    def _finished_writing(self):
589
        """Helper for finished_writing.
590
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
591
        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.
592
        finished_writing is allowed, and if it is hands off to _finished_writing
593
        to perform the action.
594
        """
595
        raise NotImplementedError(self._finished_writing)
596
597
    def read_bytes(self, count):
598
        """Read bytes from this requests response.
599
600
        This method will block and wait for count bytes to be read. It may not
601
        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.
602
        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.
603
        based mediums like HTTP.
604
        """
605
        if self._state == "writing":
606
            raise errors.WritingNotComplete(self)
607
        if self._state != "reading":
608
            raise errors.ReadingCompleted(self)
609
        return self._read_bytes(count)
610
611
    def _read_bytes(self, count):
3565.1.2 by Andrew Bennetts
Delete some more code, fix some bugs, add more comments.
612
        """Helper for SmartClientMediumRequest.read_bytes.
613
614
        read_bytes checks the state of the request to determing if bytes
615
        should be read. After that it hands off to _read_bytes to do the
616
        actual read.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
617
3565.1.2 by Andrew Bennetts
Delete some more code, fix some bugs, add more comments.
618
        By default this forwards to self._medium.read_bytes because we are
619
        operating on the medium's stream.
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
620
        """
3565.1.2 by Andrew Bennetts
Delete some more code, fix some bugs, add more comments.
621
        return self._medium.read_bytes(count)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
622
2432.2.7 by Andrew Bennetts
Use less confusing version strings, and define REQUEST_VERSION_TWO/RESPONSE_VERSION_TWO constants for them.
623
    def read_line(self):
3606.4.1 by Andrew Bennetts
Fix NotImplementedError when probing for smart protocol via HTTP.
624
        line = self._read_line()
3565.1.1 by Andrew Bennetts
Read no more then 64k at a time in the smart protocol code.
625
        if not line.endswith('\n'):
626
            # end of file encountered reading from server
627
            raise errors.ConnectionReset(
4509.2.3 by Martin Pool
Test tweaks for ConnectionReset message change
628
                "Unexpected end of message. Please check connectivity "
629
                "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.
630
        return line
631
3606.4.1 by Andrew Bennetts
Fix NotImplementedError when probing for smart protocol via HTTP.
632
    def _read_line(self):
633
        """Helper for SmartClientMediumRequest.read_line.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
634
3606.4.1 by Andrew Bennetts
Fix NotImplementedError when probing for smart protocol via HTTP.
635
        By default this forwards to self._medium._get_line because we are
636
        operating on the medium's stream.
637
        """
638
        return self._medium._get_line()
639
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
640
6060.7.1 by Jelmer Vernooij
Add vfs refuser.
641
class _VfsRefuser(object):
642
    """An object that refuses all VFS requests.
643
644
    """
645
646
    def __init__(self):
647
        client._SmartClient.hooks.install_named_hook(
6060.7.2 by Jelmer Vernooij
Fix hook installation
648
            'call', self.check_vfs, 'vfs refuser')
6060.7.1 by Jelmer Vernooij
Add vfs refuser.
649
650
    def check_vfs(self, params):
651
        try:
652
            request_method = request.request_handlers.get(params.method)
653
        except KeyError:
654
            # A method we don't know about doesn't count as a VFS method.
655
            return
6060.7.4 by Jelmer Vernooij
Update NEWS
656
        if issubclass(request_method, vfs.VfsRequest):
657
            raise errors.HpssVfsRequestNotAllowed(params.method, params.args)
6060.7.1 by Jelmer Vernooij
Add vfs refuser.
658
659
3731.2.5 by Andrew Bennetts
Rework hpss call counter.
660
class _DebugCounter(object):
661
    """An object that counts the HPSS calls made to each client medium.
662
5222.2.9 by Robert Collins
Write up some doc about bzrlib.initialize.
663
    When a medium is garbage-collected, or failing that when
664
    bzrlib.global_state exits, the total number of calls made on that medium
665
    are reported via trace.note.
3731.2.1 by Andrew Bennetts
Show total HPSS calls (if any) on stderr when -Dhpss is active.
666
    """
667
3731.2.5 by Andrew Bennetts
Rework hpss call counter.
668
    def __init__(self):
669
        self.counts = weakref.WeakKeyDictionary()
670
        client._SmartClient.hooks.install_named_hook(
671
            'call', self.increment_call_count, 'hpss call counter')
5310.1.1 by Vincent Ladeuil
Fix typo but we may want to use addCleanup instead indeed.
672
        bzrlib.global_state.cleanups.add_cleanup(self.flush_all)
3731.2.5 by Andrew Bennetts
Rework hpss call counter.
673
674
    def track(self, medium):
675
        """Start tracking calls made to a medium.
676
677
        This only keeps a weakref to the medium, so shouldn't affect the
678
        medium's lifetime.
679
        """
680
        medium_repr = repr(medium)
681
        # Add this medium to the WeakKeyDictionary
4326.2.3 by Jonathan Lange
Use as a dict.
682
        self.counts[medium] = dict(count=0, vfs_count=0,
683
                                   medium_repr=medium_repr)
3731.2.5 by Andrew Bennetts
Rework hpss call counter.
684
        # Weakref callbacks are fired in reverse order of their association
685
        # with the referenced object.  So we add a weakref *after* adding to
686
        # the WeakKeyDict so that we can report the value from it before the
687
        # entry is removed by the WeakKeyDict's own callback.
688
        ref = weakref.ref(medium, self.done)
689
690
    def increment_call_count(self, params):
691
        # Increment the count in the WeakKeyDictionary
692
        value = self.counts[params.medium]
4326.2.3 by Jonathan Lange
Use as a dict.
693
        value['count'] += 1
4476.3.15 by Andrew Bennetts
Partially working fallback for pre-1.17 servers.
694
        try:
695
            request_method = request.request_handlers.get(params.method)
696
        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.
697
            # 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.
698
            return
4326.2.1 by Jonathan Lange
Show the number of VFS calls in -Dhpss output.
699
        if issubclass(request_method, vfs.VfsRequest):
4326.2.3 by Jonathan Lange
Use as a dict.
700
            value['vfs_count'] += 1
3731.2.1 by Andrew Bennetts
Show total HPSS calls (if any) on stderr when -Dhpss is active.
701
702
    def done(self, ref):
3731.2.5 by Andrew Bennetts
Rework hpss call counter.
703
        value = self.counts[ref]
4326.2.3 by Jonathan Lange
Use as a dict.
704
        count, vfs_count, medium_repr = (
705
            value['count'], value['vfs_count'], value['medium_repr'])
3731.2.5 by Andrew Bennetts
Rework hpss call counter.
706
        # In case this callback is invoked for the same ref twice (by the
707
        # weakref callback and by the atexit function), set the call count back
708
        # to 0 so this item won't be reported twice.
4326.2.3 by Jonathan Lange
Use as a dict.
709
        value['count'] = 0
710
        value['vfs_count'] = 0
3731.2.5 by Andrew Bennetts
Rework hpss call counter.
711
        if count != 0:
6138.3.4 by Jonathan Riddell
add gettext() to uses of trace.note()
712
            trace.note(gettext('HPSS calls: {0} ({1} vfs) {2}').format(
713
                       count, vfs_count, medium_repr))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
714
3731.2.5 by Andrew Bennetts
Rework hpss call counter.
715
    def flush_all(self):
716
        for ref in list(self.counts.keys()):
717
            self.done(ref)
718
719
_debug_counter = None
6060.7.2 by Jelmer Vernooij
Fix hook installation
720
_vfs_refuser = None
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
721
722
3565.1.1 by Andrew Bennetts
Read no more then 64k at a time in the smart protocol code.
723
class SmartClientMedium(SmartMedium):
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
724
    """Smart client is a medium for sending smart protocol requests over."""
725
3431.3.3 by Andrew Bennetts
Set 'base' in SmartClientMedium base class.
726
    def __init__(self, base):
3241.1.1 by Andrew Bennetts
Shift protocol version querying from RemoteBzrDirFormat into SmartClientMedium.
727
        super(SmartClientMedium, self).__init__()
3431.3.3 by Andrew Bennetts
Set 'base' in SmartClientMedium base class.
728
        self.base = base
3241.1.4 by Andrew Bennetts
Use get_smart_medium as suggested by Robert, and deal with the fallout.
729
        self._protocol_version_error = None
3241.1.1 by Andrew Bennetts
Shift protocol version querying from RemoteBzrDirFormat into SmartClientMedium.
730
        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).
731
        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.
732
        # 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.
733
        # requests until we get an error saying otherwise.
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
734
        # _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.
735
        # 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.
736
        self._remote_version_is_before = None
3731.2.5 by Andrew Bennetts
Rework hpss call counter.
737
        # 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.
738
        if 'hpss' in debug.debug_flags:
3731.2.5 by Andrew Bennetts
Rework hpss call counter.
739
            global _debug_counter
740
            if _debug_counter is None:
741
                _debug_counter = _DebugCounter()
742
            _debug_counter.track(self)
6060.7.5 by Jelmer Vernooij
Rename hpss_no_vfs to hpss_client_no_vfs.
743
        if 'hpss_client_no_vfs' in debug.debug_flags:
6060.7.1 by Jelmer Vernooij
Add vfs refuser.
744
            global _vfs_refuser
745
            if _vfs_refuser is None:
746
                _vfs_refuser = _VfsRefuser()
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
747
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
748
    def _is_remote_before(self, version_tuple):
3502.1.1 by Matt Nordhoff
Fix a docstring typo, and a two-expression ``raise`` statement
749
        """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.
750
751
        Typical use::
752
753
            needed_version = (1, 2)
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
754
            if medium._is_remote_before(needed_version):
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
755
                fallback_to_pre_1_2_rpc()
756
            else:
757
                try:
758
                    do_1_2_rpc()
759
                except UnknownSmartMethod:
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
760
                    medium._remember_remote_is_before(needed_version)
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
761
                    fallback_to_pre_1_2_rpc()
762
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
763
        :seealso: _remember_remote_is_before
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
764
        """
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
765
        if self._remote_version_is_before is None:
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
766
            # So far, the remote side seems to support everything
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
767
            return False
768
        return version_tuple >= self._remote_version_is_before
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
769
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
770
    def _remember_remote_is_before(self, version_tuple):
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
771
        """Tell this medium that the remote side is older the given version.
772
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
773
        :seealso: _is_remote_before
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
774
        """
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
775
        if (self._remote_version_is_before is not None and
776
            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.
777
            # We have been told that the remote side is older than some version
778
            # which is newer than a previously supplied older-than version.
779
            # This indicates that some smart verb call is not guarded
780
            # 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.
781
            trace.mutter(
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
782
                "_remember_remote_is_before(%r) called, but "
783
                "_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.
784
                , version_tuple, self._remote_version_is_before)
785
            if 'hpss' in debug.debug_flags:
786
                ui.ui_factory.show_warning(
787
                    "_remember_remote_is_before(%r) called, but "
788
                    "_remember_remote_is_before(%r) was called previously."
789
                    % (version_tuple, self._remote_version_is_before))
790
            return
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
791
        self._remote_version_is_before = version_tuple
3241.1.1 by Andrew Bennetts
Shift protocol version querying from RemoteBzrDirFormat into SmartClientMedium.
792
793
    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).
794
        """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.
795
        if self._protocol_version_error is not None:
796
            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).
797
        if not self._done_hello:
3241.1.4 by Andrew Bennetts
Use get_smart_medium as suggested by Robert, and deal with the fallout.
798
            try:
799
                medium_request = self.get_request()
800
                # Send a 'hello' request in protocol version one, for maximum
801
                # backwards compatibility.
3530.1.2 by John Arbash Meinel
missed one of the imports
802
                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).
803
                client_protocol.query_version()
804
                self._done_hello = True
3241.1.4 by Andrew Bennetts
Use get_smart_medium as suggested by Robert, and deal with the fallout.
805
            except errors.SmartProtocolError, e:
806
                # Cache the error, just like we would cache a successful
807
                # result.
808
                self._protocol_version_error = e
809
                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).
810
        return '2'
811
812
    def should_probe(self):
813
        """Should RemoteBzrDirFormat.probe_transport send a smart request on
814
        this medium?
815
816
        Some transports are unambiguously smart-only; there's no need to check
817
        if the transport is able to carry smart requests, because that's all
818
        it is for.  In those cases, this method should return False.
819
820
        But some HTTP transports can sometimes fail to carry smart requests,
821
        but still be usuable for accessing remote bzrdirs via plain file
822
        accesses.  So for those transports, their media should return True here
823
        so that RemoteBzrDirFormat can determine if it is appropriate for that
824
        transport.
825
        """
826
        return False
3241.1.1 by Andrew Bennetts
Shift protocol version querying from RemoteBzrDirFormat into SmartClientMedium.
827
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
828
    def disconnect(self):
829
        """If this medium maintains a persistent connection, close it.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
830
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
831
        The default implementation does nothing.
832
        """
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
833
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
834
    def remote_path_from_transport(self, transport):
835
        """Convert transport into a path suitable for using in a request.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
836
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
837
        Note that the resulting remote path doesn't encode the host name or
838
        anything but path, so it is only safe to use it in requests sent over
839
        the medium from the matching transport.
840
        """
841
        medium_base = urlutils.join(self.base, '/')
842
        rel_url = urlutils.relative_url(medium_base, transport.base)
843
        return urllib.unquote(rel_url)
844
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
845
846
class SmartClientStreamMedium(SmartClientMedium):
847
    """Stream based medium common class.
848
849
    SmartClientStreamMediums operate on a stream. All subclasses use a common
850
    SmartClientStreamMediumRequest for their requests, and should implement
851
    _accept_bytes and _read_bytes to allow the request objects to send and
852
    receive bytes.
853
    """
854
3431.3.3 by Andrew Bennetts
Set 'base' in SmartClientMedium base class.
855
    def __init__(self, base):
856
        SmartClientMedium.__init__(self, base)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
857
        self._current_request = None
858
859
    def accept_bytes(self, bytes):
860
        self._accept_bytes(bytes)
861
862
    def __del__(self):
863
        """The SmartClientStreamMedium knows how to close the stream when it is
864
        finished with it.
865
        """
866
        self.disconnect()
867
868
    def _flush(self):
869
        """Flush the output stream.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
870
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
871
        This method is used by the SmartClientStreamMediumRequest to ensure that
872
        all data for a request is sent, to avoid long timeouts or deadlocks.
873
        """
874
        raise NotImplementedError(self._flush)
875
876
    def get_request(self):
877
        """See SmartClientMedium.get_request().
878
879
        SmartClientStreamMedium always returns a SmartClientStreamMediumRequest
880
        for get_request.
881
        """
882
        return SmartClientStreamMediumRequest(self)
883
4797.85.21 by John Arbash Meinel
Finally, we have something that can at least handle simple reconnects.
884
    def reset(self):
885
        """We have been disconnected, reset current state.
886
887
        This resets things like _current_request and connected state.
888
        """
889
        self.disconnect()
890
        self._current_request = None
891
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
892
893
class SmartSimplePipesClientMedium(SmartClientStreamMedium):
894
    """A client medium using simple pipes.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
895
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
896
    This client does not manage the pipes: it assumes they will always be open.
897
    """
898
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.
899
    def __init__(self, readable_pipe, writeable_pipe, base):
3431.3.3 by Andrew Bennetts
Set 'base' in SmartClientMedium base class.
900
        SmartClientStreamMedium.__init__(self, base)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
901
        self._readable_pipe = readable_pipe
902
        self._writeable_pipe = writeable_pipe
903
904
    def _accept_bytes(self, bytes):
905
        """See SmartClientStreamMedium.accept_bytes."""
4797.85.10 by John Arbash Meinel
Wrap the call to .write() to raise ConnectionReset on failure.
906
        try:
5050.78.5 by John Arbash Meinel
Merge the 2.1-client-read-reconnect-819604 (bug #819604) to bzr-2.2
907
            self._writeable_pipe.write(bytes)
4797.85.10 by John Arbash Meinel
Wrap the call to .write() to raise ConnectionReset on failure.
908
        except IOError, e:
909
            if e.errno in (errno.EINVAL, errno.EPIPE):
910
                raise errors.ConnectionReset(
4797.93.1 by John Arbash Meinel
Implement retrying a request as long as we haven't started consuming the body stream.
911
                    "Error trying to write to subprocess:\n%s" % (e,))
4797.85.11 by John Arbash Meinel
Maybe we can just use a regular pipe for testing, rather than spawning a subprocess.
912
            raise
3958.1.2 by Andrew Bennetts
Report network activity from more client medium implementations.
913
        self._report_activity(len(bytes), 'write')
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
914
915
    def _flush(self):
916
        """See SmartClientStreamMedium._flush()."""
4797.85.13 by John Arbash Meinel
Document the behavior of flush.
917
        # Note: If flush were to fail, we'd like to raise ConnectionReset, etc.
918
        #       However, testing shows that even when the child process is
919
        #       gone, this doesn't error.
5011.3.1 by Martin
Revert second-phase EINTR changes
920
        self._writeable_pipe.flush()
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
921
922
    def _read_bytes(self, count):
923
        """See SmartClientStreamMedium._read_bytes."""
5284.5.1 by Andrew Bennetts
Use socketpairs (rather than pipes) for SSH subprocesses where possible, and formalise some internal APIs a little more.
924
        bytes_to_read = min(count, _MAX_READ_SIZE)
925
        bytes = self._readable_pipe.read(bytes_to_read)
3958.1.2 by Andrew Bennetts
Report network activity from more client medium implementations.
926
        self._report_activity(len(bytes), 'read')
927
        return bytes
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
928
929
5284.5.1 by Andrew Bennetts
Use socketpairs (rather than pipes) for SSH subprocesses where possible, and formalise some internal APIs a little more.
930
class SSHParams(object):
5284.5.5 by Andrew Bennetts
Fix SSHParams docs.
931
    """A set of parameters for starting a remote bzr via SSH."""
5284.5.1 by Andrew Bennetts
Use socketpairs (rather than pipes) for SSH subprocesses where possible, and formalise some internal APIs a little more.
932
933
    def __init__(self, host, port=None, username=None, password=None,
934
            bzr_remote_path='bzr'):
935
        self.host = host
936
        self.port = port
937
        self.username = username
938
        self.password = password
939
        self.bzr_remote_path = bzr_remote_path
940
941
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
942
class SmartSSHClientMedium(SmartClientStreamMedium):
5284.5.1 by Andrew Bennetts
Use socketpairs (rather than pipes) for SSH subprocesses where possible, and formalise some internal APIs a little more.
943
    """A client medium using SSH.
4797.85.20 by John Arbash Meinel
Pull in the code from bzr.dev that changes SmartSSHClientMedium
944
5050.78.5 by John Arbash Meinel
Merge the 2.1-client-read-reconnect-819604 (bug #819604) to bzr-2.2
945
    It delegates IO to a SmartSimplePipesClientMedium or
5284.5.1 by Andrew Bennetts
Use socketpairs (rather than pipes) for SSH subprocesses where possible, and formalise some internal APIs a little more.
946
    SmartClientAlreadyConnectedSocketMedium (depending on platform).
947
    """
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
948
5284.5.1 by Andrew Bennetts
Use socketpairs (rather than pipes) for SSH subprocesses where possible, and formalise some internal APIs a little more.
949
    def __init__(self, base, ssh_params, vendor=None):
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
950
        """Creates a client that will connect on the first use.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
951
5284.5.1 by Andrew Bennetts
Use socketpairs (rather than pipes) for SSH subprocesses where possible, and formalise some internal APIs a little more.
952
        :param ssh_params: A SSHParams instance.
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
953
        :param vendor: An optional override for the ssh vendor to use. See
954
            bzrlib.transport.ssh for details on ssh vendors.
955
        """
5284.5.1 by Andrew Bennetts
Use socketpairs (rather than pipes) for SSH subprocesses where possible, and formalise some internal APIs a little more.
956
        self._real_medium = None
957
        self._ssh_params = ssh_params
4964.2.5 by Martin Pool
Make sure variables used in repr are set early in initialization
958
        # for the benefit of progress making a short description of this
959
        # transport
960
        self._scheme = 'bzr+ssh'
4100.1.5 by Martin Pool
Fix crash in SSHSmartClientStreamMedium repr.
961
        # SmartClientStreamMedium stores the repr of this object in its
962
        # _DebugCounter so we have to store all the values used in our repr
963
        # method before calling the super init.
964
        SmartClientStreamMedium.__init__(self, base)
5284.5.1 by Andrew Bennetts
Use socketpairs (rather than pipes) for SSH subprocesses where possible, and formalise some internal APIs a little more.
965
        self._vendor = vendor
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
966
        self._ssh_connection = None
4100.1.1 by Martin Pool
Cleanup and add SmartSSHClientMedium repr
967
968
    def __repr__(self):
5284.5.1 by Andrew Bennetts
Use socketpairs (rather than pipes) for SSH subprocesses where possible, and formalise some internal APIs a little more.
969
        if self._ssh_params.port is None:
4964.2.4 by Martin Pool
Tweak SSHSmartClientMedium to look better when there's no port
970
            maybe_port = ''
971
        else:
5284.5.1 by Andrew Bennetts
Use socketpairs (rather than pipes) for SSH subprocesses where possible, and formalise some internal APIs a little more.
972
            maybe_port = ':%s' % self._ssh_params.port
6242.1.1 by Jelmer Vernooij
Cope with username being None in SmartSSHMedium.__repr__.
973
        if self._ssh_params.username is None:
974
            maybe_user = ''
975
        else:
976
            maybe_user = '%s@' % self._ssh_params.username
977
        return "%s(%s://%s%s%s/)" % (
4100.1.1 by Martin Pool
Cleanup and add SmartSSHClientMedium repr
978
            self.__class__.__name__,
4964.2.3 by Martin Pool
Tweak SmartSSHClientMedium repr
979
            self._scheme,
6242.1.1 by Jelmer Vernooij
Cope with username being None in SmartSSHMedium.__repr__.
980
            maybe_user,
5284.5.1 by Andrew Bennetts
Use socketpairs (rather than pipes) for SSH subprocesses where possible, and formalise some internal APIs a little more.
981
            self._ssh_params.host,
4964.2.4 by Martin Pool
Tweak SSHSmartClientMedium to look better when there's no port
982
            maybe_port)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
983
984
    def _accept_bytes(self, bytes):
985
        """See SmartClientStreamMedium.accept_bytes."""
986
        self._ensure_connection()
5284.5.6 by Andrew Bennetts
Tweaks prompted by Robert's review.
987
        self._real_medium.accept_bytes(bytes)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
988
989
    def disconnect(self):
990
        """See SmartClientMedium.disconnect()."""
5284.5.1 by Andrew Bennetts
Use socketpairs (rather than pipes) for SSH subprocesses where possible, and formalise some internal APIs a little more.
991
        if self._real_medium is not None:
992
            self._real_medium.disconnect()
993
            self._real_medium = None
994
        if self._ssh_connection is not None:
995
            self._ssh_connection.close()
996
            self._ssh_connection = None
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
997
998
    def _ensure_connection(self):
999
        """Connect this medium if not already connected."""
5284.5.1 by Andrew Bennetts
Use socketpairs (rather than pipes) for SSH subprocesses where possible, and formalise some internal APIs a little more.
1000
        if self._real_medium is not None:
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
1001
            return
1002
        if self._vendor is None:
1003
            vendor = ssh._get_ssh_vendor()
1004
        else:
1005
            vendor = self._vendor
5284.5.1 by Andrew Bennetts
Use socketpairs (rather than pipes) for SSH subprocesses where possible, and formalise some internal APIs a little more.
1006
        self._ssh_connection = vendor.connect_ssh(self._ssh_params.username,
1007
                self._ssh_params.password, self._ssh_params.host,
1008
                self._ssh_params.port,
1009
                command=[self._ssh_params.bzr_remote_path, 'serve', '--inet',
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
1010
                         '--directory=/', '--allow-writes'])
5284.5.1 by Andrew Bennetts
Use socketpairs (rather than pipes) for SSH subprocesses where possible, and formalise some internal APIs a little more.
1011
        io_kind, io_object = self._ssh_connection.get_sock_or_pipes()
1012
        if io_kind == 'socket':
1013
            self._real_medium = SmartClientAlreadyConnectedSocketMedium(
1014
                self.base, io_object)
1015
        elif io_kind == 'pipes':
1016
            read_from, write_to = io_object
1017
            self._real_medium = SmartSimplePipesClientMedium(
1018
                read_from, write_to, self.base)
1019
        else:
1020
            raise AssertionError(
1021
                "Unexpected io_kind %r from %r"
1022
                % (io_kind, self._ssh_connection))
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
1023
1024
    def _flush(self):
1025
        """See SmartClientStreamMedium._flush()."""
5284.5.1 by Andrew Bennetts
Use socketpairs (rather than pipes) for SSH subprocesses where possible, and formalise some internal APIs a little more.
1026
        self._real_medium._flush()
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
1027
1028
    def _read_bytes(self, count):
1029
        """See SmartClientStreamMedium.read_bytes."""
5284.5.1 by Andrew Bennetts
Use socketpairs (rather than pipes) for SSH subprocesses where possible, and formalise some internal APIs a little more.
1030
        if self._real_medium is None:
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
1031
            raise errors.MediumNotConnected(self)
5284.5.6 by Andrew Bennetts
Tweaks prompted by Robert's review.
1032
        return self._real_medium.read_bytes(count)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
1033
1034
3004.2.1 by Vincent Ladeuil
Fix 150860 by leaving port as user specified it.
1035
# Port 4155 is the default port for bzr://, registered with IANA.
3665.4.1 by Jelmer Vernooij
Support IPv6 in the smart server.
1036
BZR_DEFAULT_INTERFACE = None
3004.2.1 by Vincent Ladeuil
Fix 150860 by leaving port as user specified it.
1037
BZR_DEFAULT_PORT = 4155
1038
1039
5284.5.1 by Andrew Bennetts
Use socketpairs (rather than pipes) for SSH subprocesses where possible, and formalise some internal APIs a little more.
1040
class SmartClientSocketMedium(SmartClientStreamMedium):
5284.5.6 by Andrew Bennetts
Tweaks prompted by Robert's review.
1041
    """A client medium using a socket.
1042
    
1043
    This class isn't usable directly.  Use one of its subclasses instead.
1044
    """
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1045
5284.5.1 by Andrew Bennetts
Use socketpairs (rather than pipes) for SSH subprocesses where possible, and formalise some internal APIs a little more.
1046
    def __init__(self, base):
3431.3.3 by Andrew Bennetts
Set 'base' in SmartClientMedium base class.
1047
        SmartClientStreamMedium.__init__(self, base)
5284.5.1 by Andrew Bennetts
Use socketpairs (rather than pipes) for SSH subprocesses where possible, and formalise some internal APIs a little more.
1048
        self._socket = None
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
1049
        self._connected = False
1050
1051
    def _accept_bytes(self, bytes):
1052
        """See SmartClientMedium.accept_bytes."""
1053
        self._ensure_connection()
5011.3.9 by Andrew Bennetts
Remove _send_bytes_chunked.
1054
        osutils.send_all(self._socket, bytes, self._report_activity)
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
1055
5284.5.6 by Andrew Bennetts
Tweaks prompted by Robert's review.
1056
    def _ensure_connection(self):
1057
        """Connect this medium if not already connected."""
1058
        raise NotImplementedError(self._ensure_connection)
1059
5284.5.1 by Andrew Bennetts
Use socketpairs (rather than pipes) for SSH subprocesses where possible, and formalise some internal APIs a little more.
1060
    def _flush(self):
1061
        """See SmartClientStreamMedium._flush().
1062
5284.5.6 by Andrew Bennetts
Tweaks prompted by Robert's review.
1063
        For sockets we do no flushing. For TCP sockets we may want to turn off
1064
        TCP_NODELAY and add a means to do a flush, but that can be done in the
1065
        future.
5284.5.1 by Andrew Bennetts
Use socketpairs (rather than pipes) for SSH subprocesses where possible, and formalise some internal APIs a little more.
1066
        """
1067
1068
    def _read_bytes(self, count):
1069
        """See SmartClientMedium.read_bytes."""
1070
        if not self._connected:
1071
            raise errors.MediumNotConnected(self)
1072
        return osutils.read_bytes_from_socket(
1073
            self._socket, self._report_activity)
1074
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
1075
    def disconnect(self):
1076
        """See SmartClientMedium.disconnect()."""
1077
        if not self._connected:
1078
            return
5011.3.1 by Martin
Revert second-phase EINTR changes
1079
        self._socket.close()
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
1080
        self._socket = None
1081
        self._connected = False
1082
5284.5.1 by Andrew Bennetts
Use socketpairs (rather than pipes) for SSH subprocesses where possible, and formalise some internal APIs a little more.
1083
1084
class SmartTCPClientMedium(SmartClientSocketMedium):
5284.5.6 by Andrew Bennetts
Tweaks prompted by Robert's review.
1085
    """A client medium that creates a TCP connection."""
5284.5.1 by Andrew Bennetts
Use socketpairs (rather than pipes) for SSH subprocesses where possible, and formalise some internal APIs a little more.
1086
1087
    def __init__(self, host, port, base):
1088
        """Creates a client that will connect on the first use."""
1089
        SmartClientSocketMedium.__init__(self, base)
1090
        self._host = host
1091
        self._port = port
1092
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
1093
    def _ensure_connection(self):
1094
        """Connect this medium if not already connected."""
1095
        if self._connected:
1096
            return
3004.2.1 by Vincent Ladeuil
Fix 150860 by leaving port as user specified it.
1097
        if self._port is None:
1098
            port = BZR_DEFAULT_PORT
1099
        else:
1100
            port = int(self._port)
3711.2.2 by Jelmer Vernooij
Avoid using AI_ADDRCONFIG since it's not portable.
1101
        try:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1102
            sockaddrs = socket.getaddrinfo(self._host, port, socket.AF_UNSPEC,
3711.2.2 by Jelmer Vernooij
Avoid using AI_ADDRCONFIG since it's not portable.
1103
                socket.SOCK_STREAM, 0, 0)
1104
        except socket.gaierror, (err_num, err_msg):
1105
            raise errors.ConnectionError("failed to lookup %s:%d: %s" %
1106
                    (self._host, port, err_msg))
3711.2.3 by Jelmer Vernooij
Add comment.
1107
        # Initialize err in case there are no addresses returned:
3665.4.2 by Jelmer Vernooij
Fall through to next available address if previous fails.
1108
        err = socket.error("no address found for %s" % self._host)
3665.4.1 by Jelmer Vernooij
Support IPv6 in the smart server.
1109
        for (family, socktype, proto, canonname, sockaddr) in sockaddrs:
1110
            try:
3665.4.2 by Jelmer Vernooij
Fall through to next available address if previous fails.
1111
                self._socket = socket.socket(family, socktype, proto)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1112
                self._socket.setsockopt(socket.IPPROTO_TCP,
3665.4.2 by Jelmer Vernooij
Fall through to next available address if previous fails.
1113
                                        socket.TCP_NODELAY, 1)
3665.4.1 by Jelmer Vernooij
Support IPv6 in the smart server.
1114
                self._socket.connect(sockaddr)
1115
            except socket.error, err:
3665.4.2 by Jelmer Vernooij
Fall through to next available address if previous fails.
1116
                if self._socket is not None:
1117
                    self._socket.close()
1118
                self._socket = None
1119
                continue
1120
            break
1121
        if self._socket is None:
1122
            # socket errors either have a (string) or (errno, string) as their
1123
            # args.
1124
            if type(err.args) is str:
1125
                err_msg = err.args
1126
            else:
1127
                err_msg = err.args[1]
1128
            raise errors.ConnectionError("failed to connect to %s:%d: %s" %
1129
                    (self._host, port, err_msg))
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
1130
        self._connected = True
1131
5284.5.1 by Andrew Bennetts
Use socketpairs (rather than pipes) for SSH subprocesses where possible, and formalise some internal APIs a little more.
1132
1133
class SmartClientAlreadyConnectedSocketMedium(SmartClientSocketMedium):
5284.5.3 by Andrew Bennetts
Docstring tweaks.
1134
    """A client medium for an already connected socket.
5284.5.1 by Andrew Bennetts
Use socketpairs (rather than pipes) for SSH subprocesses where possible, and formalise some internal APIs a little more.
1135
    
1136
    Note that this class will assume it "owns" the socket, so it will close it
1137
    when its disconnect method is called.
1138
    """
1139
1140
    def __init__(self, base, sock):
1141
        SmartClientSocketMedium.__init__(self, base)
1142
        self._socket = sock
1143
        self._connected = True
1144
1145
    def _ensure_connection(self):
1146
        # Already connected, by definition!  So nothing to do.
1147
        pass
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
1148
1149
1150
class SmartClientStreamMediumRequest(SmartClientMediumRequest):
1151
    """A SmartClientMediumRequest that works with an SmartClientStreamMedium."""
1152
1153
    def __init__(self, medium):
1154
        SmartClientMediumRequest.__init__(self, medium)
1155
        # check that we are safe concurrency wise. If some streams start
1156
        # allowing concurrent requests - i.e. via multiplexing - then this
1157
        # assert should be moved to SmartClientStreamMedium.get_request,
1158
        # and the setting/unsetting of _current_request likewise moved into
1159
        # that class : but its unneeded overhead for now. RBC 20060922
1160
        if self._medium._current_request is not None:
1161
            raise errors.TooManyConcurrentRequests(self._medium)
1162
        self._medium._current_request = self
1163
1164
    def _accept_bytes(self, bytes):
1165
        """See SmartClientMediumRequest._accept_bytes.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1166
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
1167
        This forwards to self._medium._accept_bytes because we are operating
1168
        on the mediums stream.
1169
        """
1170
        self._medium._accept_bytes(bytes)
1171
1172
    def _finished_reading(self):
1173
        """See SmartClientMediumRequest._finished_reading.
1174
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1175
        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.
1176
        request to be created.
1177
        """
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1178
        if self._medium._current_request is not self:
1179
            raise AssertionError()
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
1180
        self._medium._current_request = None
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1181
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
1182
    def _finished_writing(self):
1183
        """See SmartClientMediumRequest._finished_writing.
1184
1185
        This invokes self._medium._flush to ensure all bytes are transmitted.
1186
        """
1187
        self._medium._flush()