/brz/remove-bazaar

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