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