~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/smart/server.py

  • Committer: Patch Queue Manager
  • Date: 2016-01-15 09:21:49 UTC
  • mfrom: (6606.2.1 autodoc-unicode)
  • Revision ID: pqm@pqm.ubuntu.com-20160115092149-z5f4sfq3jvaz0enb
(vila) Fix autodoc runner when LANG=C. (Jelmer Vernooij)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2010 Canonical Ltd
 
1
# Copyright (C) 2006-2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
16
16
 
17
17
"""Server for smart-server protocol."""
18
18
 
 
19
from __future__ import absolute_import
 
20
 
19
21
import errno
20
22
import os.path
21
 
import select
22
23
import socket
23
24
import sys
 
25
import time
24
26
import threading
25
27
 
26
 
from bzrlib.hooks import HookPoint, Hooks
 
28
from bzrlib.hooks import Hooks
27
29
from bzrlib import (
28
30
    errors,
29
31
    trace,
30
 
    transport,
 
32
    transport as _mod_transport,
31
33
)
 
34
from bzrlib.i18n import gettext
32
35
from bzrlib.lazy_import import lazy_import
33
36
lazy_import(globals(), """
34
 
from bzrlib.smart import medium
 
37
from bzrlib.smart import (
 
38
    medium,
 
39
    signals,
 
40
    )
35
41
from bzrlib.transport import (
36
42
    chroot,
37
 
    get_transport,
38
43
    pathfilter,
39
44
    )
40
45
from bzrlib import (
 
46
    config,
41
47
    urlutils,
42
48
    )
43
49
""")
52
58
    hooks: An instance of SmartServerHooks.
53
59
    """
54
60
 
55
 
    def __init__(self, backing_transport, root_client_path='/'):
 
61
    # This is the timeout on the socket we use .accept() on. It is exposed here
 
62
    # so the test suite can set it faster. (It thread.interrupt_main() will not
 
63
    # fire a KeyboardInterrupt during socket.accept)
 
64
    _ACCEPT_TIMEOUT = 1.0
 
65
    _SHUTDOWN_POLL_TIMEOUT = 1.0
 
66
    _LOG_WAITING_TIMEOUT = 10.0
 
67
 
 
68
    _timer = time.time
 
69
 
 
70
    def __init__(self, backing_transport, root_client_path='/',
 
71
                 client_timeout=None):
56
72
        """Construct a new server.
57
73
 
58
74
        To actually start it running, call either start_background_thread or
61
77
        :param backing_transport: The transport to serve.
62
78
        :param root_client_path: The client path that will correspond to root
63
79
            of backing_transport.
 
80
        :param client_timeout: See SmartServerSocketStreamMedium's timeout
 
81
            parameter.
64
82
        """
65
83
        self.backing_transport = backing_transport
66
84
        self.root_client_path = root_client_path
 
85
        self._client_timeout = client_timeout
 
86
        self._active_connections = []
 
87
        # This is set to indicate we want to wait for clients to finish before
 
88
        # we disconnect.
 
89
        self._gracefully_stopping = False
67
90
 
68
91
    def start_server(self, host, port):
69
92
        """Create the server listening socket.
95
118
        self._sockname = self._server_socket.getsockname()
96
119
        self.port = self._sockname[1]
97
120
        self._server_socket.listen(1)
98
 
        self._server_socket.settimeout(1)
 
121
        self._server_socket.settimeout(self._ACCEPT_TIMEOUT)
 
122
        # Once we start accept()ing connections, we set started.
99
123
        self._started = threading.Event()
 
124
        # Once we stop accept()ing connections (and are closing the socket) we
 
125
        # set _stopped
100
126
        self._stopped = threading.Event()
 
127
        # Once we have finished waiting for all clients, etc. We set
 
128
        # _fully_stopped
 
129
        self._fully_stopped = threading.Event()
101
130
 
102
131
    def _backing_urls(self):
103
132
        # There are three interesting urls:
105
134
        # The URL that a commit done on the same machine as the server will
106
135
        # have within the servers space. (e.g. file:///home/user/source)
107
136
        # The URL that will be given to other hooks in the same process -
108
 
        # the URL of the backing transport itself. (e.g. chroot+:///)
 
137
        # the URL of the backing transport itself. (e.g. filtered-36195:///)
109
138
        # We need all three because:
110
139
        #  * other machines see the first
111
140
        #  * local commits on this machine should be able to be mapped to
136
165
        for hook in SmartTCPServer.hooks['server_stopped']:
137
166
            hook(backing_urls, self.get_url())
138
167
 
 
168
    def _stop_gracefully(self):
 
169
        trace.note(gettext('Requested to stop gracefully'))
 
170
        self._should_terminate = True
 
171
        self._gracefully_stopping = True
 
172
        for handler, _ in self._active_connections:
 
173
            handler._stop_gracefully()
 
174
 
 
175
    def _wait_for_clients_to_disconnect(self):
 
176
        self._poll_active_connections()
 
177
        if not self._active_connections:
 
178
            return
 
179
        trace.note(gettext('Waiting for %d client(s) to finish')
 
180
                   % (len(self._active_connections),))
 
181
        t_next_log = self._timer() + self._LOG_WAITING_TIMEOUT
 
182
        while self._active_connections:
 
183
            now = self._timer()
 
184
            if now >= t_next_log:
 
185
                trace.note(gettext('Still waiting for %d client(s) to finish')
 
186
                           % (len(self._active_connections),))
 
187
                t_next_log = now + self._LOG_WAITING_TIMEOUT
 
188
            self._poll_active_connections(self._SHUTDOWN_POLL_TIMEOUT)
 
189
 
139
190
    def serve(self, thread_name_suffix=''):
 
191
        # Note: There is a temptation to do
 
192
        #       signals.register_on_hangup(id(self), self._stop_gracefully)
 
193
        #       However, that creates a temporary object which is a bound
 
194
        #       method. signals._on_sighup is a WeakKeyDictionary so it
 
195
        #       immediately gets garbage collected, because nothing else
 
196
        #       references it. Instead, we need to keep a real reference to the
 
197
        #       bound method for the lifetime of the serve() function.
 
198
        stop_gracefully = self._stop_gracefully
 
199
        signals.register_on_hangup(id(self), stop_gracefully)
140
200
        self._should_terminate = False
141
201
        # for hooks we are letting code know that a server has started (and
142
202
        # later stopped).
152
212
                        pass
153
213
                    except self._socket_error, e:
154
214
                        # if the socket is closed by stop_background_thread
155
 
                        # we might get a EBADF here, any other socket errors
156
 
                        # should get logged.
157
 
                        if e.args[0] != errno.EBADF:
158
 
                            trace.warning("listening socket error: %s", e)
 
215
                        # we might get a EBADF here, or if we get a signal we
 
216
                        # can get EINTR, any other socket errors should get
 
217
                        # logged.
 
218
                        if e.args[0] not in (errno.EBADF, errno.EINTR):
 
219
                            trace.warning(gettext("listening socket error: %s")
 
220
                                          % (e,))
159
221
                    else:
160
222
                        if self._should_terminate:
 
223
                            conn.close()
161
224
                            break
162
225
                        self.serve_conn(conn, thread_name_suffix)
 
226
                    # Cleanout any threads that have finished processing.
 
227
                    self._poll_active_connections()
163
228
            except KeyboardInterrupt:
164
229
                # dont log when CTRL-C'd.
165
230
                raise
167
232
                trace.report_exception(sys.exc_info(), sys.stderr)
168
233
                raise
169
234
        finally:
170
 
            self._stopped.set()
171
235
            try:
172
236
                # ensure the server socket is closed.
173
237
                self._server_socket.close()
174
238
            except self._socket_error:
175
239
                # ignore errors on close
176
240
                pass
 
241
            self._stopped.set()
 
242
            signals.unregister_on_hangup(id(self))
177
243
            self.run_server_stopped_hooks()
 
244
        if self._gracefully_stopping:
 
245
            self._wait_for_clients_to_disconnect()
 
246
        self._fully_stopped.set()
178
247
 
179
248
    def get_url(self):
180
249
        """Return the url of the server"""
181
 
        return "bzr://%s:%d/" % self._sockname
 
250
        return "bzr://%s:%s/" % (self._sockname[0], self._sockname[1])
 
251
 
 
252
    def _make_handler(self, conn):
 
253
        return medium.SmartServerSocketStreamMedium(
 
254
            conn, self.backing_transport, self.root_client_path,
 
255
            timeout=self._client_timeout)
 
256
 
 
257
    def _poll_active_connections(self, timeout=0.0):
 
258
        """Check to see if any active connections have finished.
 
259
 
 
260
        This will iterate through self._active_connections, and update any
 
261
        connections that are finished.
 
262
 
 
263
        :param timeout: The timeout to pass to thread.join(). By default, we
 
264
            set it to 0, so that we don't hang if threads are not done yet.
 
265
        :return: None
 
266
        """
 
267
        still_active = []
 
268
        for handler, thread in self._active_connections:
 
269
            thread.join(timeout)
 
270
            if thread.isAlive():
 
271
                still_active.append((handler, thread))
 
272
        self._active_connections = still_active
182
273
 
183
274
    def serve_conn(self, conn, thread_name_suffix):
184
275
        # For WIN32, where the timeout value from the listening socket
185
276
        # propagates to the newly accepted socket.
186
277
        conn.setblocking(True)
187
278
        conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
188
 
        handler = medium.SmartServerSocketStreamMedium(
189
 
            conn, self.backing_transport, self.root_client_path)
190
279
        thread_name = 'smart-server-child' + thread_name_suffix
 
280
        handler = self._make_handler(conn)
191
281
        connection_thread = threading.Thread(
192
282
            None, handler.serve, name=thread_name)
193
 
        # FIXME: This thread is never joined, it should at least be collected
194
 
        # somewhere so that tests that want to check for leaked threads can get
195
 
        # rid of them -- vila 20100531
 
283
        self._active_connections.append((handler, connection_thread))
196
284
        connection_thread.setDaemon(True)
197
285
        connection_thread.start()
198
286
        return connection_thread
241
329
        These are all empty initially, because by default nothing should get
242
330
        notified.
243
331
        """
244
 
        Hooks.__init__(self)
245
 
        self.create_hook(HookPoint('server_started',
 
332
        Hooks.__init__(self, "bzrlib.smart.server", "SmartTCPServer.hooks")
 
333
        self.add_hook('server_started',
246
334
            "Called by the bzr server when it starts serving a directory. "
247
335
            "server_started is called with (backing urls, public url), "
248
336
            "where backing_url is a list of URLs giving the "
249
337
            "server-specific directory locations, and public_url is the "
250
 
            "public URL for the directory being served.", (0, 16), None))
251
 
        self.create_hook(HookPoint('server_started_ex',
 
338
            "public URL for the directory being served.", (0, 16))
 
339
        self.add_hook('server_started_ex',
252
340
            "Called by the bzr server when it starts serving a directory. "
253
341
            "server_started is called with (backing_urls, server_obj).",
254
 
            (1, 17), None))
255
 
        self.create_hook(HookPoint('server_stopped',
 
342
            (1, 17))
 
343
        self.add_hook('server_stopped',
256
344
            "Called by the bzr server when it stops serving a directory. "
257
345
            "server_stopped is called with the same parameters as the "
258
 
            "server_started hook: (backing_urls, public_url).", (0, 16), None))
 
346
            "server_started hook: (backing_urls, public_url).", (0, 16))
 
347
        self.add_hook('server_exception',
 
348
            "Called by the bzr server when an exception occurs. "
 
349
            "server_exception is called with the sys.exc_info() tuple "
 
350
            "return true for the hook if the exception has been handled, "
 
351
            "in which case the server will exit normally.", (2, 4))
259
352
 
260
353
SmartTCPServer.hooks = SmartServerHooks()
261
354
 
327
420
        chroot_server = chroot.ChrootServer(transport)
328
421
        chroot_server.start_server()
329
422
        self.cleanups.append(chroot_server.stop_server)
330
 
        transport = get_transport(chroot_server.get_url())
 
423
        transport = _mod_transport.get_transport_from_url(chroot_server.get_url())
331
424
        if self.base_path is not None:
332
425
            # Decorate the server's backing transport with a filter that can
333
426
            # expand homedirs.
334
427
            expand_userdirs = self._make_expand_userdirs_filter(transport)
335
428
            expand_userdirs.start_server()
336
429
            self.cleanups.append(expand_userdirs.stop_server)
337
 
            transport = get_transport(expand_userdirs.get_url())
 
430
            transport = _mod_transport.get_transport_from_url(expand_userdirs.get_url())
338
431
        self.transport = transport
339
432
 
340
 
    def _make_smart_server(self, host, port, inet):
 
433
    def _get_stdin_stdout(self):
 
434
        return sys.stdin, sys.stdout
 
435
 
 
436
    def _make_smart_server(self, host, port, inet, timeout):
 
437
        if timeout is None:
 
438
            c = config.GlobalStack()
 
439
            timeout = c.get('serve.client_timeout')
341
440
        if inet:
 
441
            stdin, stdout = self._get_stdin_stdout()
342
442
            smart_server = medium.SmartServerPipeStreamMedium(
343
 
                sys.stdin, sys.stdout, self.transport)
 
443
                stdin, stdout, self.transport, timeout=timeout)
344
444
        else:
345
445
            if host is None:
346
446
                host = medium.BZR_DEFAULT_INTERFACE
347
447
            if port is None:
348
448
                port = medium.BZR_DEFAULT_PORT
349
 
            smart_server = SmartTCPServer(self.transport)
 
449
            smart_server = SmartTCPServer(self.transport,
 
450
                                          client_timeout=timeout)
350
451
            smart_server.start_server(host, port)
351
 
            trace.note('listening on port: %s' % smart_server.port)
 
452
            trace.note(gettext('listening on port: %s') % smart_server.port)
352
453
        self.smart_server = smart_server
353
454
 
354
455
    def _change_globals(self):
365
466
        self.cleanups.append(restore_default_ui_factory_and_lockdir_timeout)
366
467
        ui.ui_factory = ui.SilentUIFactory()
367
468
        lockdir._DEFAULT_TIMEOUT_SECONDS = 0
 
469
        orig = signals.install_sighup_handler()
 
470
        def restore_signals():
 
471
            signals.restore_sighup_handler(orig)
 
472
        self.cleanups.append(restore_signals)
368
473
 
369
 
    def set_up(self, transport, host, port, inet):
 
474
    def set_up(self, transport, host, port, inet, timeout):
370
475
        self._make_backing_transport(transport)
371
 
        self._make_smart_server(host, port, inet)
 
476
        self._make_smart_server(host, port, inet, timeout)
372
477
        self._change_globals()
373
478
 
374
479
    def tear_down(self):
376
481
            cleanup()
377
482
 
378
483
 
379
 
def serve_bzr(transport, host=None, port=None, inet=False):
 
484
def serve_bzr(transport, host=None, port=None, inet=False, timeout=None):
380
485
    """This is the default implementation of 'bzr serve'.
381
 
    
 
486
 
382
487
    It creates a TCP or pipe smart server on 'transport, and runs it.  The
383
488
    transport will be decorated with a chroot and pathfilter (using
384
489
    os.path.expanduser).
385
490
    """
386
491
    bzr_server = BzrServerFactory()
387
492
    try:
388
 
        bzr_server.set_up(transport, host, port, inet)
 
493
        bzr_server.set_up(transport, host, port, inet, timeout)
389
494
        bzr_server.smart_server.serve()
 
495
    except:
 
496
        hook_caught_exception = False
 
497
        for hook in SmartTCPServer.hooks['server_exception']:
 
498
            hook_caught_exception = hook(sys.exc_info())
 
499
        if not hook_caught_exception:
 
500
            raise
390
501
    finally:
391
502
        bzr_server.tear_down()
392