/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
3374.1.1 by Martin Pool
Set SO_REUSEADDR on server sockets (#164288)
1
# Copyright (C) 2006, 2007, 2008 Canonical Ltd
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
2018.5.19 by Andrew Bennetts
Add docstrings to all the new modules, and a few other places.
17
"""Server for smart-server protocol."""
18
2400.1.7 by Andrew Bennetts
Merge from bzr.dev.
19
import errno
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
20
import socket
3374.1.1 by Martin Pool
Set SO_REUSEADDR on server sockets (#164288)
21
import sys
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
22
import threading
23
2400.1.7 by Andrew Bennetts
Merge from bzr.dev.
24
from bzrlib.hooks import Hooks
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
25
from bzrlib import (
2634.1.1 by Robert Collins
(robertc) Reinstate the accidentally backed out external_url patch.
26
    errors,
2018.5.15 by Andrew Bennetts
Tidy some imports, and bugs introduced when adding server.py
27
    trace,
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
28
    transport,
29
)
3224.5.5 by Andrew Bennetts
Don't import bzrlib.smart.medium from bzrlib.smart.server until it's needed. This helps the bzr-dbus plugin import faster.
30
from bzrlib.lazy_import import lazy_import
31
lazy_import(globals(), """
32
from bzrlib.smart import medium
33
""")
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
34
35
36
class SmartTCPServer(object):
37
    """Listens on a TCP socket and accepts connections from smart clients.
2018.5.139 by Andrew Bennetts
Merge from bzr.dev, resolving conflicts.
38
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
39
    Each connection will be served by a SmartServerSocketStreamMedium running in
2018.5.139 by Andrew Bennetts
Merge from bzr.dev, resolving conflicts.
40
    a thread.
2400.1.7 by Andrew Bennetts
Merge from bzr.dev.
41
42
    hooks: An instance of SmartServerHooks.
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
43
    """
44
2692.1.14 by Andrew Bennetts
All WSGI tests passing, and manual testing works too.
45
    def __init__(self, backing_transport, host='127.0.0.1', port=0,
46
                 root_client_path='/'):
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
47
        """Construct a new server.
48
49
        To actually start it running, call either start_background_thread or
50
        serve.
51
2692.1.14 by Andrew Bennetts
All WSGI tests passing, and manual testing works too.
52
        :param backing_transport: The transport to serve.
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
53
        :param host: Name of the interface to listen on.
54
        :param port: TCP port to listen on, or 0 to allocate a transient port.
2692.1.14 by Andrew Bennetts
All WSGI tests passing, and manual testing works too.
55
        :param root_client_path: The client path that will correspond to root
56
            of backing_transport.
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
57
        """
2400.1.7 by Andrew Bennetts
Merge from bzr.dev.
58
        # let connections timeout so that we get a chance to terminate
59
        # Keep a reference to the exceptions we want to catch because the socket
60
        # module's globals get set to None during interpreter shutdown.
61
        from socket import timeout as socket_timeout
62
        from socket import error as socket_error
63
        self._socket_error = socket_error
64
        self._socket_timeout = socket_timeout
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
65
        self._server_socket = socket.socket()
3374.1.1 by Martin Pool
Set SO_REUSEADDR on server sockets (#164288)
66
        # SO_REUSERADDR has a different meaning on Windows
67
        if sys.platform != 'win32':
68
            self._server_socket.setsockopt(socket.SOL_SOCKET,
69
                socket.SO_REUSEADDR, 1)
3365.1.1 by Andrea Corbellini
Handle errors raised by socket.bind() (bug 200575)
70
        try:
71
            self._server_socket.bind((host, port))
72
        except self._socket_error, message:
73
            raise errors.CannotBindAddress(host, port, message)
2400.1.7 by Andrew Bennetts
Merge from bzr.dev.
74
        self._sockname = self._server_socket.getsockname()
75
        self.port = self._sockname[1]
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
76
        self._server_socket.listen(1)
77
        self._server_socket.settimeout(1)
78
        self.backing_transport = backing_transport
2400.1.7 by Andrew Bennetts
Merge from bzr.dev.
79
        self._started = threading.Event()
80
        self._stopped = threading.Event()
2692.1.14 by Andrew Bennetts
All WSGI tests passing, and manual testing works too.
81
        self.root_client_path = root_client_path
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
82
3245.4.28 by Andrew Bennetts
Remove another XXX, and include test ID in smart server thread names.
83
    def serve(self, thread_name_suffix=''):
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
84
        self._should_terminate = False
2634.1.1 by Robert Collins
(robertc) Reinstate the accidentally backed out external_url patch.
85
        # for hooks we are letting code know that a server has started (and
86
        # later stopped).
87
        # There are three interesting urls:
88
        # The URL the server can be contacted on. (e.g. bzr://host/)
89
        # The URL that a commit done on the same machine as the server will
90
        # have within the servers space. (e.g. file:///home/user/source)
91
        # The URL that will be given to other hooks in the same process -
92
        # the URL of the backing transport itself. (e.g. chroot+:///)
93
        # We need all three because:
94
        #  * other machines see the first
95
        #  * local commits on this machine should be able to be mapped to
96
        #    this server 
97
        #  * commits the server does itself need to be mapped across to this
98
        #    server.
99
        # The latter two urls are different aliases to the servers url,
100
        # so we group those in a list - as there might be more aliases 
101
        # in the future.
102
        backing_urls = [self.backing_transport.base]
103
        try:
104
            backing_urls.append(self.backing_transport.external_url())
105
        except errors.InProcessTransport:
106
            pass
2400.1.7 by Andrew Bennetts
Merge from bzr.dev.
107
        for hook in SmartTCPServer.hooks['server_started']:
2634.1.1 by Robert Collins
(robertc) Reinstate the accidentally backed out external_url patch.
108
            hook(backing_urls, self.get_url())
2400.1.7 by Andrew Bennetts
Merge from bzr.dev.
109
        self._started.set()
110
        try:
111
            try:
112
                while not self._should_terminate:
113
                    try:
114
                        conn, client_addr = self._server_socket.accept()
115
                    except self._socket_timeout:
116
                        # just check if we're asked to stop
117
                        pass
118
                    except self._socket_error, e:
119
                        # if the socket is closed by stop_background_thread
120
                        # we might get a EBADF here, any other socket errors
121
                        # should get logged.
122
                        if e.args[0] != errno.EBADF:
123
                            trace.warning("listening socket error: %s", e)
124
                    else:
3245.4.28 by Andrew Bennetts
Remove another XXX, and include test ID in smart server thread names.
125
                        self.serve_conn(conn, thread_name_suffix)
2400.1.7 by Andrew Bennetts
Merge from bzr.dev.
126
            except KeyboardInterrupt:
127
                # dont log when CTRL-C'd.
128
                raise
129
            except Exception, e:
130
                trace.error("Unhandled smart server error.")
131
                trace.log_exception_quietly()
132
                raise
133
        finally:
134
            self._stopped.set()
135
            try:
136
                # ensure the server socket is closed.
137
                self._server_socket.close()
138
            except self._socket_error:
139
                # ignore errors on close
140
                pass
141
            for hook in SmartTCPServer.hooks['server_stopped']:
2634.1.1 by Robert Collins
(robertc) Reinstate the accidentally backed out external_url patch.
142
                hook(backing_urls, self.get_url())
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
143
144
    def get_url(self):
145
        """Return the url of the server"""
2400.1.7 by Andrew Bennetts
Merge from bzr.dev.
146
        return "bzr://%s:%d/" % self._sockname
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
147
3245.4.28 by Andrew Bennetts
Remove another XXX, and include test ID in smart server thread names.
148
    def serve_conn(self, conn, thread_name_suffix):
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
149
        # For WIN32, where the timeout value from the listening socket
150
        # propogates to the newly accepted socket.
151
        conn.setblocking(True)
152
        conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
3224.5.5 by Andrew Bennetts
Don't import bzrlib.smart.medium from bzrlib.smart.server until it's needed. This helps the bzr-dbus plugin import faster.
153
        handler = medium.SmartServerSocketStreamMedium(
2692.1.11 by Andrew Bennetts
Improve test coverage by making SmartTCPServer_for_testing by default create a server that does not serve the backing transport's root at its own root. This mirrors the way most HTTP smart servers are configured.
154
            conn, self.backing_transport, self.root_client_path)
3245.4.28 by Andrew Bennetts
Remove another XXX, and include test ID in smart server thread names.
155
        thread_name = 'smart-server-child' + thread_name_suffix
156
        connection_thread = threading.Thread(
157
            None, handler.serve, name=thread_name)
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
158
        connection_thread.setDaemon(True)
159
        connection_thread.start()
160
3245.4.28 by Andrew Bennetts
Remove another XXX, and include test ID in smart server thread names.
161
    def start_background_thread(self, thread_name_suffix=''):
2400.1.7 by Andrew Bennetts
Merge from bzr.dev.
162
        self._started.clear()
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
163
        self._server_thread = threading.Thread(None,
3245.4.28 by Andrew Bennetts
Remove another XXX, and include test ID in smart server thread names.
164
                self.serve, args=(thread_name_suffix,),
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
165
                name='server-' + self.get_url())
166
        self._server_thread.setDaemon(True)
167
        self._server_thread.start()
2400.1.7 by Andrew Bennetts
Merge from bzr.dev.
168
        self._started.wait()
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
169
170
    def stop_background_thread(self):
2400.1.7 by Andrew Bennetts
Merge from bzr.dev.
171
        self._stopped.clear()
172
        # tell the main loop to quit on the next iteration.
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
173
        self._should_terminate = True
2400.1.7 by Andrew Bennetts
Merge from bzr.dev.
174
        # close the socket - gives error to connections from here on in,
175
        # rather than a connection reset error to connections made during
176
        # the period between setting _should_terminate = True and 
177
        # the current request completing/aborting. It may also break out the
178
        # main loop if it was currently in accept() (on some platforms).
179
        try:
180
            self._server_socket.close()
181
        except self._socket_error:
182
            # ignore errors on close
183
            pass
184
        if not self._stopped.isSet():
185
            # server has not stopped (though it may be stopping)
186
            # its likely in accept(), so give it a connection
187
            temp_socket = socket.socket()
188
            temp_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
189
            if not temp_socket.connect_ex(self._sockname):
190
                # and close it immediately: we dont choose to send any requests.
191
                temp_socket.close()
192
        self._stopped.wait()
193
        self._server_thread.join()
194
195
196
class SmartServerHooks(Hooks):
197
    """Hooks for the smart server."""
198
199
    def __init__(self):
200
        """Create the default hooks.
201
202
        These are all empty initially, because by default nothing should get
203
        notified.
204
        """
205
        Hooks.__init__(self)
206
        # Introduced in 0.16:
207
        # invoked whenever the server starts serving a directory.
2634.1.1 by Robert Collins
(robertc) Reinstate the accidentally backed out external_url patch.
208
        # The api signature is (backing urls, public url).
2400.1.7 by Andrew Bennetts
Merge from bzr.dev.
209
        self['server_started'] = []
210
        # Introduced in 0.16:
211
        # invoked whenever the server stops serving a directory.
2634.1.1 by Robert Collins
(robertc) Reinstate the accidentally backed out external_url patch.
212
        # The api signature is (backing urls, public url).
2400.1.7 by Andrew Bennetts
Merge from bzr.dev.
213
        self['server_stopped'] = []
214
215
SmartTCPServer.hooks = SmartServerHooks()
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
216
2400.1.2 by Andrew Bennetts
Move SmartTCPServer classes into bzrlib/smart/server.py
217
218
class SmartTCPServer_for_testing(SmartTCPServer):
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
219
    """Server suitable for use by transport tests.
220
    
2400.1.2 by Andrew Bennetts
Move SmartTCPServer classes into bzrlib/smart/server.py
221
    This server is backed by the process's cwd.
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
222
    """
223
3245.4.28 by Andrew Bennetts
Remove another XXX, and include test ID in smart server thread names.
224
    def __init__(self, thread_name_suffix=''):
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
225
        SmartTCPServer.__init__(self, None)
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.
226
        self.client_path_extra = None
3245.4.28 by Andrew Bennetts
Remove another XXX, and include test ID in smart server thread names.
227
        self.thread_name_suffix = thread_name_suffix
2400.1.2 by Andrew Bennetts
Move SmartTCPServer classes into bzrlib/smart/server.py
228
        
229
    def get_backing_transport(self, backing_transport_server):
230
        """Get a backing transport from a server we are decorating."""
2018.5.104 by Andrew Bennetts
Completely rework chrooted transports.
231
        return transport.get_transport(backing_transport_server.get_url())
2400.1.2 by Andrew Bennetts
Move SmartTCPServer classes into bzrlib/smart/server.py
232
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.
233
    def setUp(self, backing_transport_server=None,
234
              client_path_extra='/extra/'):
235
        """Set up server for testing.
236
        
237
        :param backing_transport_server: backing server to use.  If not
238
            specified, a LocalURLServer at the current working directory will
239
            be used.
240
        :param client_path_extra: a path segment starting with '/' to append to
241
            the root URL for this server.  For instance, a value of '/foo/bar/'
242
            will mean the root of the backing transport will be published at a
243
            URL like `bzr://127.0.0.1:nnnn/foo/bar/`, rather than
244
            `bzr://127.0.0.1:nnnn/`.  Default value is `extra`, so that tests
245
            by default will fail unless they do the necessary path translation.
246
        """
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
247
        if not client_path_extra.startswith('/'):
248
            raise ValueError(client_path_extra)
2018.5.104 by Andrew Bennetts
Completely rework chrooted transports.
249
        from bzrlib.transport.chroot import ChrootServer
2018.5.47 by Andrew Bennetts
Make SmartTCPServer_for_Testing.setUp's backing_transport_server argument optional.
250
        if backing_transport_server is None:
251
            from bzrlib.transport.local import LocalURLServer
252
            backing_transport_server = LocalURLServer()
2018.5.104 by Andrew Bennetts
Completely rework chrooted transports.
253
        self.chroot_server = ChrootServer(
254
            self.get_backing_transport(backing_transport_server))
255
        self.chroot_server.setUp()
256
        self.backing_transport = transport.get_transport(
257
            self.chroot_server.get_url())
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.
258
        self.root_client_path = self.client_path_extra = client_path_extra
3245.4.28 by Andrew Bennetts
Remove another XXX, and include test ID in smart server thread names.
259
        self.start_background_thread(self.thread_name_suffix)
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
260
261
    def tearDown(self):
262
        self.stop_background_thread()
2018.5.104 by Andrew Bennetts
Completely rework chrooted transports.
263
        self.chroot_server.tearDown()
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
264
2692.1.11 by Andrew Bennetts
Improve test coverage by making SmartTCPServer_for_testing by default create a server that does not serve the backing transport's root at its own root. This mirrors the way most HTTP smart servers are configured.
265
    def get_url(self):
266
        url = super(SmartTCPServer_for_testing, self).get_url()
267
        return url[:-1] + self.client_path_extra
268
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
269
    def get_bogus_url(self):
270
        """Return a URL which will fail to connect"""
271
        return 'bzr://127.0.0.1:1/'
272
273
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
274
class ReadonlySmartTCPServer_for_testing(SmartTCPServer_for_testing):
275
    """Get a readonly server for testing."""
276
277
    def get_backing_transport(self, backing_transport_server):
278
        """Get a backing transport from a server we are decorating."""
2018.5.104 by Andrew Bennetts
Completely rework chrooted transports.
279
        url = 'readonly+' + backing_transport_server.get_url()
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
280
        return transport.get_transport(url)
3453.5.1 by Andrew Bennetts
Add {bzrdir,repository,branch}_implementations tests for Remote objects using protocol v2 and pre-1.6 RPCs.
281
282
283
class SmartTCPServer_for_testing_v2_only(SmartTCPServer_for_testing):
284
    """A variation of SmartTCPServer_for_testing that limits the client to
285
    using RPCs in protocol v2 (i.e. bzr <= 1.5).
286
    """
287
288
    def get_url(self):
289
        url = super(SmartTCPServer_for_testing_v2_only, self).get_url()
290
        url = 'bzr-v2://' + url[len('bzr://'):]
291
        return url
292
293
294
class ReadonlySmartTCPServer_for_testing_v2_only(SmartTCPServer_for_testing_v2_only):
295
    """Get a readonly server for testing."""
296
297
    def get_backing_transport(self, backing_transport_server):
298
        """Get a backing transport from a server we are decorating."""
299
        url = 'readonly+' + backing_transport_server.get_url()
300
        return transport.get_transport(url)
301
302