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