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