~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/smart/server.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2011-05-04 12:10:51 UTC
  • mfrom: (5819.1.4 777007-developer-doc)
  • Revision ID: pqm@pqm.ubuntu.com-20110504121051-aovlsmqiivjmc4fc
(jelmer) Small fixes to developer documentation. (Jonathan Riddell)

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006-2010 Canonical Ltd
 
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
"""Server for smart-server protocol."""
 
18
 
 
19
import errno
 
20
import os.path
 
21
import socket
 
22
import sys
 
23
import threading
 
24
 
 
25
from bzrlib.hooks import Hooks
 
26
from bzrlib import (
 
27
    errors,
 
28
    trace,
 
29
    transport as _mod_transport,
 
30
)
 
31
from bzrlib.lazy_import import lazy_import
 
32
lazy_import(globals(), """
 
33
from bzrlib.smart import medium
 
34
from bzrlib.transport import (
 
35
    chroot,
 
36
    pathfilter,
 
37
    )
 
38
from bzrlib import (
 
39
    urlutils,
 
40
    )
 
41
""")
 
42
 
 
43
 
 
44
class SmartTCPServer(object):
 
45
    """Listens on a TCP socket and accepts connections from smart clients.
 
46
 
 
47
    Each connection will be served by a SmartServerSocketStreamMedium running in
 
48
    a thread.
 
49
 
 
50
    hooks: An instance of SmartServerHooks.
 
51
    """
 
52
 
 
53
    def __init__(self, backing_transport, root_client_path='/'):
 
54
        """Construct a new server.
 
55
 
 
56
        To actually start it running, call either start_background_thread or
 
57
        serve.
 
58
 
 
59
        :param backing_transport: The transport to serve.
 
60
        :param root_client_path: The client path that will correspond to root
 
61
            of backing_transport.
 
62
        """
 
63
        self.backing_transport = backing_transport
 
64
        self.root_client_path = root_client_path
 
65
 
 
66
    def start_server(self, host, port):
 
67
        """Create the server listening socket.
 
68
 
 
69
        :param host: Name of the interface to listen on.
 
70
        :param port: TCP port to listen on, or 0 to allocate a transient port.
 
71
        """
 
72
        # let connections timeout so that we get a chance to terminate
 
73
        # Keep a reference to the exceptions we want to catch because the socket
 
74
        # module's globals get set to None during interpreter shutdown.
 
75
        from socket import timeout as socket_timeout
 
76
        from socket import error as socket_error
 
77
        self._socket_error = socket_error
 
78
        self._socket_timeout = socket_timeout
 
79
        addrs = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
 
80
            socket.SOCK_STREAM, 0, socket.AI_PASSIVE)[0]
 
81
 
 
82
        (family, socktype, proto, canonname, sockaddr) = addrs
 
83
 
 
84
        self._server_socket = socket.socket(family, socktype, proto)
 
85
        # SO_REUSERADDR has a different meaning on Windows
 
86
        if sys.platform != 'win32':
 
87
            self._server_socket.setsockopt(socket.SOL_SOCKET,
 
88
                socket.SO_REUSEADDR, 1)
 
89
        try:
 
90
            self._server_socket.bind(sockaddr)
 
91
        except self._socket_error, message:
 
92
            raise errors.CannotBindAddress(host, port, message)
 
93
        self._sockname = self._server_socket.getsockname()
 
94
        self.port = self._sockname[1]
 
95
        self._server_socket.listen(1)
 
96
        self._server_socket.settimeout(1)
 
97
        self._started = threading.Event()
 
98
        self._stopped = threading.Event()
 
99
 
 
100
    def _backing_urls(self):
 
101
        # There are three interesting urls:
 
102
        # The URL the server can be contacted on. (e.g. bzr://host/)
 
103
        # The URL that a commit done on the same machine as the server will
 
104
        # have within the servers space. (e.g. file:///home/user/source)
 
105
        # The URL that will be given to other hooks in the same process -
 
106
        # the URL of the backing transport itself. (e.g. filtered-36195:///)
 
107
        # We need all three because:
 
108
        #  * other machines see the first
 
109
        #  * local commits on this machine should be able to be mapped to
 
110
        #    this server
 
111
        #  * commits the server does itself need to be mapped across to this
 
112
        #    server.
 
113
        # The latter two urls are different aliases to the servers url,
 
114
        # so we group those in a list - as there might be more aliases
 
115
        # in the future.
 
116
        urls = [self.backing_transport.base]
 
117
        try:
 
118
            urls.append(self.backing_transport.external_url())
 
119
        except errors.InProcessTransport:
 
120
            pass
 
121
        return urls
 
122
 
 
123
    def run_server_started_hooks(self, backing_urls=None):
 
124
        if backing_urls is None:
 
125
            backing_urls = self._backing_urls()
 
126
        for hook in SmartTCPServer.hooks['server_started']:
 
127
            hook(backing_urls, self.get_url())
 
128
        for hook in SmartTCPServer.hooks['server_started_ex']:
 
129
            hook(backing_urls, self)
 
130
 
 
131
    def run_server_stopped_hooks(self, backing_urls=None):
 
132
        if backing_urls is None:
 
133
            backing_urls = self._backing_urls()
 
134
        for hook in SmartTCPServer.hooks['server_stopped']:
 
135
            hook(backing_urls, self.get_url())
 
136
 
 
137
    def serve(self, thread_name_suffix=''):
 
138
        self._should_terminate = False
 
139
        # for hooks we are letting code know that a server has started (and
 
140
        # later stopped).
 
141
        self.run_server_started_hooks()
 
142
        self._started.set()
 
143
        try:
 
144
            try:
 
145
                while not self._should_terminate:
 
146
                    try:
 
147
                        conn, client_addr = self._server_socket.accept()
 
148
                    except self._socket_timeout:
 
149
                        # just check if we're asked to stop
 
150
                        pass
 
151
                    except self._socket_error, e:
 
152
                        # if the socket is closed by stop_background_thread
 
153
                        # we might get a EBADF here, any other socket errors
 
154
                        # should get logged.
 
155
                        if e.args[0] != errno.EBADF:
 
156
                            trace.warning("listening socket error: %s", e)
 
157
                    else:
 
158
                        if self._should_terminate:
 
159
                            break
 
160
                        self.serve_conn(conn, thread_name_suffix)
 
161
            except KeyboardInterrupt:
 
162
                # dont log when CTRL-C'd.
 
163
                raise
 
164
            except Exception, e:
 
165
                trace.report_exception(sys.exc_info(), sys.stderr)
 
166
                raise
 
167
        finally:
 
168
            self._stopped.set()
 
169
            try:
 
170
                # ensure the server socket is closed.
 
171
                self._server_socket.close()
 
172
            except self._socket_error:
 
173
                # ignore errors on close
 
174
                pass
 
175
            self.run_server_stopped_hooks()
 
176
 
 
177
    def get_url(self):
 
178
        """Return the url of the server"""
 
179
        return "bzr://%s:%s/" % (self._sockname[0], self._sockname[1])
 
180
 
 
181
    def serve_conn(self, conn, thread_name_suffix):
 
182
        # For WIN32, where the timeout value from the listening socket
 
183
        # propagates to the newly accepted socket.
 
184
        conn.setblocking(True)
 
185
        conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
 
186
        handler = medium.SmartServerSocketStreamMedium(
 
187
            conn, self.backing_transport, self.root_client_path)
 
188
        thread_name = 'smart-server-child' + thread_name_suffix
 
189
        connection_thread = threading.Thread(
 
190
            None, handler.serve, name=thread_name)
 
191
        # FIXME: This thread is never joined, it should at least be collected
 
192
        # somewhere so that tests that want to check for leaked threads can get
 
193
        # rid of them -- vila 20100531
 
194
        connection_thread.setDaemon(True)
 
195
        connection_thread.start()
 
196
        return connection_thread
 
197
 
 
198
    def start_background_thread(self, thread_name_suffix=''):
 
199
        self._started.clear()
 
200
        self._server_thread = threading.Thread(None,
 
201
                self.serve, args=(thread_name_suffix,),
 
202
                name='server-' + self.get_url())
 
203
        self._server_thread.setDaemon(True)
 
204
        self._server_thread.start()
 
205
        self._started.wait()
 
206
 
 
207
    def stop_background_thread(self):
 
208
        self._stopped.clear()
 
209
        # tell the main loop to quit on the next iteration.
 
210
        self._should_terminate = True
 
211
        # close the socket - gives error to connections from here on in,
 
212
        # rather than a connection reset error to connections made during
 
213
        # the period between setting _should_terminate = True and
 
214
        # the current request completing/aborting. It may also break out the
 
215
        # main loop if it was currently in accept() (on some platforms).
 
216
        try:
 
217
            self._server_socket.close()
 
218
        except self._socket_error:
 
219
            # ignore errors on close
 
220
            pass
 
221
        if not self._stopped.isSet():
 
222
            # server has not stopped (though it may be stopping)
 
223
            # its likely in accept(), so give it a connection
 
224
            temp_socket = socket.socket()
 
225
            temp_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
 
226
            if not temp_socket.connect_ex(self._sockname):
 
227
                # and close it immediately: we dont choose to send any requests.
 
228
                temp_socket.close()
 
229
        self._stopped.wait()
 
230
        self._server_thread.join()
 
231
 
 
232
 
 
233
class SmartServerHooks(Hooks):
 
234
    """Hooks for the smart server."""
 
235
 
 
236
    def __init__(self):
 
237
        """Create the default hooks.
 
238
 
 
239
        These are all empty initially, because by default nothing should get
 
240
        notified.
 
241
        """
 
242
        Hooks.__init__(self, "bzrlib.smart.server", "SmartTCPServer.hooks")
 
243
        self.add_hook('server_started',
 
244
            "Called by the bzr server when it starts serving a directory. "
 
245
            "server_started is called with (backing urls, public url), "
 
246
            "where backing_url is a list of URLs giving the "
 
247
            "server-specific directory locations, and public_url is the "
 
248
            "public URL for the directory being served.", (0, 16))
 
249
        self.add_hook('server_started_ex',
 
250
            "Called by the bzr server when it starts serving a directory. "
 
251
            "server_started is called with (backing_urls, server_obj).",
 
252
            (1, 17))
 
253
        self.add_hook('server_stopped',
 
254
            "Called by the bzr server when it stops serving a directory. "
 
255
            "server_stopped is called with the same parameters as the "
 
256
            "server_started hook: (backing_urls, public_url).", (0, 16))
 
257
 
 
258
SmartTCPServer.hooks = SmartServerHooks()
 
259
 
 
260
 
 
261
def _local_path_for_transport(transport):
 
262
    """Return a local path for transport, if reasonably possible.
 
263
    
 
264
    This function works even if transport's url has a "readonly+" prefix,
 
265
    unlike local_path_from_url.
 
266
    
 
267
    This essentially recovers the --directory argument the user passed to "bzr
 
268
    serve" from the transport passed to serve_bzr.
 
269
    """
 
270
    try:
 
271
        base_url = transport.external_url()
 
272
    except (errors.InProcessTransport, NotImplementedError):
 
273
        return None
 
274
    else:
 
275
        # Strip readonly prefix
 
276
        if base_url.startswith('readonly+'):
 
277
            base_url = base_url[len('readonly+'):]
 
278
        try:
 
279
            return urlutils.local_path_from_url(base_url)
 
280
        except errors.InvalidURL:
 
281
            return None
 
282
 
 
283
 
 
284
class BzrServerFactory(object):
 
285
    """Helper class for serve_bzr."""
 
286
 
 
287
    def __init__(self, userdir_expander=None, get_base_path=None):
 
288
        self.cleanups = []
 
289
        self.base_path = None
 
290
        self.backing_transport = None
 
291
        if userdir_expander is None:
 
292
            userdir_expander = os.path.expanduser
 
293
        self.userdir_expander = userdir_expander
 
294
        if get_base_path is None:
 
295
            get_base_path = _local_path_for_transport
 
296
        self.get_base_path = get_base_path
 
297
 
 
298
    def _expand_userdirs(self, path):
 
299
        """Translate /~/ or /~user/ to e.g. /home/foo, using
 
300
        self.userdir_expander (os.path.expanduser by default).
 
301
 
 
302
        If the translated path would fall outside base_path, or the path does
 
303
        not start with ~, then no translation is applied.
 
304
 
 
305
        If the path is inside, it is adjusted to be relative to the base path.
 
306
 
 
307
        e.g. if base_path is /home, and the expanded path is /home/joe, then
 
308
        the translated path is joe.
 
309
        """
 
310
        result = path
 
311
        if path.startswith('~'):
 
312
            expanded = self.userdir_expander(path)
 
313
            if not expanded.endswith('/'):
 
314
                expanded += '/'
 
315
            if expanded.startswith(self.base_path):
 
316
                result = expanded[len(self.base_path):]
 
317
        return result
 
318
 
 
319
    def _make_expand_userdirs_filter(self, transport):
 
320
        return pathfilter.PathFilteringServer(transport, self._expand_userdirs)
 
321
 
 
322
    def _make_backing_transport(self, transport):
 
323
        """Chroot transport, and decorate with userdir expander."""
 
324
        self.base_path = self.get_base_path(transport)
 
325
        chroot_server = chroot.ChrootServer(transport)
 
326
        chroot_server.start_server()
 
327
        self.cleanups.append(chroot_server.stop_server)
 
328
        transport = _mod_transport.get_transport(chroot_server.get_url())
 
329
        if self.base_path is not None:
 
330
            # Decorate the server's backing transport with a filter that can
 
331
            # expand homedirs.
 
332
            expand_userdirs = self._make_expand_userdirs_filter(transport)
 
333
            expand_userdirs.start_server()
 
334
            self.cleanups.append(expand_userdirs.stop_server)
 
335
            transport = _mod_transport.get_transport(expand_userdirs.get_url())
 
336
        self.transport = transport
 
337
 
 
338
    def _make_smart_server(self, host, port, inet):
 
339
        if inet:
 
340
            smart_server = medium.SmartServerPipeStreamMedium(
 
341
                sys.stdin, sys.stdout, self.transport)
 
342
        else:
 
343
            if host is None:
 
344
                host = medium.BZR_DEFAULT_INTERFACE
 
345
            if port is None:
 
346
                port = medium.BZR_DEFAULT_PORT
 
347
            smart_server = SmartTCPServer(self.transport)
 
348
            smart_server.start_server(host, port)
 
349
            trace.note('listening on port: %s' % smart_server.port)
 
350
        self.smart_server = smart_server
 
351
 
 
352
    def _change_globals(self):
 
353
        from bzrlib import lockdir, ui
 
354
        # For the duration of this server, no UI output is permitted. note
 
355
        # that this may cause problems with blackbox tests. This should be
 
356
        # changed with care though, as we dont want to use bandwidth sending
 
357
        # progress over stderr to smart server clients!
 
358
        old_factory = ui.ui_factory
 
359
        old_lockdir_timeout = lockdir._DEFAULT_TIMEOUT_SECONDS
 
360
        def restore_default_ui_factory_and_lockdir_timeout():
 
361
            ui.ui_factory = old_factory
 
362
            lockdir._DEFAULT_TIMEOUT_SECONDS = old_lockdir_timeout
 
363
        self.cleanups.append(restore_default_ui_factory_and_lockdir_timeout)
 
364
        ui.ui_factory = ui.SilentUIFactory()
 
365
        lockdir._DEFAULT_TIMEOUT_SECONDS = 0
 
366
 
 
367
    def set_up(self, transport, host, port, inet):
 
368
        self._make_backing_transport(transport)
 
369
        self._make_smart_server(host, port, inet)
 
370
        self._change_globals()
 
371
 
 
372
    def tear_down(self):
 
373
        for cleanup in reversed(self.cleanups):
 
374
            cleanup()
 
375
 
 
376
 
 
377
def serve_bzr(transport, host=None, port=None, inet=False):
 
378
    """This is the default implementation of 'bzr serve'.
 
379
    
 
380
    It creates a TCP or pipe smart server on 'transport, and runs it.  The
 
381
    transport will be decorated with a chroot and pathfilter (using
 
382
    os.path.expanduser).
 
383
    """
 
384
    bzr_server = BzrServerFactory()
 
385
    try:
 
386
        bzr_server.set_up(transport, host, port, inet)
 
387
        bzr_server.smart_server.serve()
 
388
    finally:
 
389
        bzr_server.tear_down()
 
390