/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/smart/server.py

  • Committer: John Arbash Meinel
  • Date: 2009-06-02 21:11:18 UTC
  • mto: This revision was merged to the branch mainline in revision 4412.
  • Revision ID: john@arbash-meinel.com-20090602211118-fjsx4dxokahrqkrr
Change groupcompress.DeltaIndex to be lazy about indexing the first source.

This changes the performance characteristics of 'commit', especially of large files.
The main benefit is that during commit, we won't be doing any deltas as we add
all new content to a new group anyway.
Thus we know that we won't ever use the delta index we were creating, so
we can save both time and memory by never creating the index until it is
needed.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006, 2007, 2008 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 socket
 
21
import sys
 
22
import threading
 
23
 
 
24
from bzrlib.hooks import HookPoint, Hooks
 
25
from bzrlib import (
 
26
    errors,
 
27
    trace,
 
28
    transport,
 
29
)
 
30
from bzrlib.lazy_import import lazy_import
 
31
lazy_import(globals(), """
 
32
from bzrlib.smart import medium
 
33
""")
 
34
 
 
35
 
 
36
class SmartTCPServer(object):
 
37
    """Listens on a TCP socket and accepts connections from smart clients.
 
38
 
 
39
    Each connection will be served by a SmartServerSocketStreamMedium running in
 
40
    a thread.
 
41
 
 
42
    hooks: An instance of SmartServerHooks.
 
43
    """
 
44
 
 
45
    def __init__(self, backing_transport, host='127.0.0.1', port=0,
 
46
                 root_client_path='/'):
 
47
        """Construct a new server.
 
48
 
 
49
        To actually start it running, call either start_background_thread or
 
50
        serve.
 
51
 
 
52
        :param backing_transport: The transport to serve.
 
53
        :param host: Name of the interface to listen on.
 
54
        :param port: TCP port to listen on, or 0 to allocate a transient port.
 
55
        :param root_client_path: The client path that will correspond to root
 
56
            of backing_transport.
 
57
        """
 
58
        # let connections timeout so that we get a chance to terminate
 
59
        # Keep a reference to the exceptions we want to catch because the socket
 
60
        # module's globals get set to None during interpreter shutdown.
 
61
        from socket import timeout as socket_timeout
 
62
        from socket import error as socket_error
 
63
        self._socket_error = socket_error
 
64
        self._socket_timeout = socket_timeout
 
65
        addrs = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
 
66
            socket.SOCK_STREAM, 0, socket.AI_PASSIVE)[0]
 
67
 
 
68
        (family, socktype, proto, canonname, sockaddr) = addrs
 
69
 
 
70
        self._server_socket = socket.socket(family, socktype, proto)
 
71
        # SO_REUSERADDR has a different meaning on Windows
 
72
        if sys.platform != 'win32':
 
73
            self._server_socket.setsockopt(socket.SOL_SOCKET,
 
74
                socket.SO_REUSEADDR, 1)
 
75
        try:
 
76
            self._server_socket.bind(sockaddr)
 
77
        except self._socket_error, message:
 
78
            raise errors.CannotBindAddress(host, port, message)
 
79
        self._sockname = self._server_socket.getsockname()
 
80
        self.port = self._sockname[1]
 
81
        self._server_socket.listen(1)
 
82
        self._server_socket.settimeout(1)
 
83
        self.backing_transport = backing_transport
 
84
        self._started = threading.Event()
 
85
        self._stopped = threading.Event()
 
86
        self.root_client_path = root_client_path
 
87
 
 
88
    def serve(self, thread_name_suffix=''):
 
89
        self._should_terminate = False
 
90
        # for hooks we are letting code know that a server has started (and
 
91
        # later stopped).
 
92
        # There are three interesting urls:
 
93
        # The URL the server can be contacted on. (e.g. bzr://host/)
 
94
        # The URL that a commit done on the same machine as the server will
 
95
        # have within the servers space. (e.g. file:///home/user/source)
 
96
        # The URL that will be given to other hooks in the same process -
 
97
        # the URL of the backing transport itself. (e.g. chroot+:///)
 
98
        # We need all three because:
 
99
        #  * other machines see the first
 
100
        #  * local commits on this machine should be able to be mapped to
 
101
        #    this server
 
102
        #  * commits the server does itself need to be mapped across to this
 
103
        #    server.
 
104
        # The latter two urls are different aliases to the servers url,
 
105
        # so we group those in a list - as there might be more aliases
 
106
        # in the future.
 
107
        backing_urls = [self.backing_transport.base]
 
108
        try:
 
109
            backing_urls.append(self.backing_transport.external_url())
 
110
        except errors.InProcessTransport:
 
111
            pass
 
112
        for hook in SmartTCPServer.hooks['server_started']:
 
113
            hook(backing_urls, self.get_url())
 
114
        self._started.set()
 
115
        try:
 
116
            try:
 
117
                while not self._should_terminate:
 
118
                    try:
 
119
                        conn, client_addr = self._server_socket.accept()
 
120
                    except self._socket_timeout:
 
121
                        # just check if we're asked to stop
 
122
                        pass
 
123
                    except self._socket_error, e:
 
124
                        # if the socket is closed by stop_background_thread
 
125
                        # we might get a EBADF here, any other socket errors
 
126
                        # should get logged.
 
127
                        if e.args[0] != errno.EBADF:
 
128
                            trace.warning("listening socket error: %s", e)
 
129
                    else:
 
130
                        self.serve_conn(conn, thread_name_suffix)
 
131
            except KeyboardInterrupt:
 
132
                # dont log when CTRL-C'd.
 
133
                raise
 
134
            except Exception, e:
 
135
                trace.error("Unhandled smart server error.")
 
136
                trace.log_exception_quietly()
 
137
                raise
 
138
        finally:
 
139
            self._stopped.set()
 
140
            try:
 
141
                # ensure the server socket is closed.
 
142
                self._server_socket.close()
 
143
            except self._socket_error:
 
144
                # ignore errors on close
 
145
                pass
 
146
            for hook in SmartTCPServer.hooks['server_stopped']:
 
147
                hook(backing_urls, self.get_url())
 
148
 
 
149
    def get_url(self):
 
150
        """Return the url of the server"""
 
151
        return "bzr://%s:%d/" % self._sockname
 
152
 
 
153
    def serve_conn(self, conn, thread_name_suffix):
 
154
        # For WIN32, where the timeout value from the listening socket
 
155
        # propagates to the newly accepted socket.
 
156
        conn.setblocking(True)
 
157
        conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
 
158
        handler = medium.SmartServerSocketStreamMedium(
 
159
            conn, self.backing_transport, self.root_client_path)
 
160
        thread_name = 'smart-server-child' + thread_name_suffix
 
161
        connection_thread = threading.Thread(
 
162
            None, handler.serve, name=thread_name)
 
163
        connection_thread.setDaemon(True)
 
164
        connection_thread.start()
 
165
 
 
166
    def start_background_thread(self, thread_name_suffix=''):
 
167
        self._started.clear()
 
168
        self._server_thread = threading.Thread(None,
 
169
                self.serve, args=(thread_name_suffix,),
 
170
                name='server-' + self.get_url())
 
171
        self._server_thread.setDaemon(True)
 
172
        self._server_thread.start()
 
173
        self._started.wait()
 
174
 
 
175
    def stop_background_thread(self):
 
176
        self._stopped.clear()
 
177
        # tell the main loop to quit on the next iteration.
 
178
        self._should_terminate = True
 
179
        # close the socket - gives error to connections from here on in,
 
180
        # rather than a connection reset error to connections made during
 
181
        # the period between setting _should_terminate = True and
 
182
        # the current request completing/aborting. It may also break out the
 
183
        # main loop if it was currently in accept() (on some platforms).
 
184
        try:
 
185
            self._server_socket.close()
 
186
        except self._socket_error:
 
187
            # ignore errors on close
 
188
            pass
 
189
        if not self._stopped.isSet():
 
190
            # server has not stopped (though it may be stopping)
 
191
            # its likely in accept(), so give it a connection
 
192
            temp_socket = socket.socket()
 
193
            temp_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
 
194
            if not temp_socket.connect_ex(self._sockname):
 
195
                # and close it immediately: we dont choose to send any requests.
 
196
                temp_socket.close()
 
197
        self._stopped.wait()
 
198
        self._server_thread.join()
 
199
 
 
200
 
 
201
class SmartServerHooks(Hooks):
 
202
    """Hooks for the smart server."""
 
203
 
 
204
    def __init__(self):
 
205
        """Create the default hooks.
 
206
 
 
207
        These are all empty initially, because by default nothing should get
 
208
        notified.
 
209
        """
 
210
        Hooks.__init__(self)
 
211
        self.create_hook(HookPoint('server_started',
 
212
            "Called by the bzr server when it starts serving a directory. "
 
213
            "server_started is called with (backing urls, public url), "
 
214
            "where backing_url is a list of URLs giving the "
 
215
            "server-specific directory locations, and public_url is the "
 
216
            "public URL for the directory being served.", (0, 16), None))
 
217
        self.create_hook(HookPoint('server_stopped',
 
218
            "Called by the bzr server when it stops serving a directory. "
 
219
            "server_stopped is called with the same parameters as the "
 
220
            "server_started hook: (backing_urls, public_url).", (0, 16), None))
 
221
 
 
222
SmartTCPServer.hooks = SmartServerHooks()
 
223
 
 
224
 
 
225
class SmartTCPServer_for_testing(SmartTCPServer):
 
226
    """Server suitable for use by transport tests.
 
227
 
 
228
    This server is backed by the process's cwd.
 
229
    """
 
230
 
 
231
    def __init__(self, thread_name_suffix=''):
 
232
        SmartTCPServer.__init__(self, None)
 
233
        self.client_path_extra = None
 
234
        self.thread_name_suffix = thread_name_suffix
 
235
 
 
236
    def get_backing_transport(self, backing_transport_server):
 
237
        """Get a backing transport from a server we are decorating."""
 
238
        return transport.get_transport(backing_transport_server.get_url())
 
239
 
 
240
    def setUp(self, backing_transport_server=None,
 
241
              client_path_extra='/extra/'):
 
242
        """Set up server for testing.
 
243
 
 
244
        :param backing_transport_server: backing server to use.  If not
 
245
            specified, a LocalURLServer at the current working directory will
 
246
            be used.
 
247
        :param client_path_extra: a path segment starting with '/' to append to
 
248
            the root URL for this server.  For instance, a value of '/foo/bar/'
 
249
            will mean the root of the backing transport will be published at a
 
250
            URL like `bzr://127.0.0.1:nnnn/foo/bar/`, rather than
 
251
            `bzr://127.0.0.1:nnnn/`.  Default value is `extra`, so that tests
 
252
            by default will fail unless they do the necessary path translation.
 
253
        """
 
254
        if not client_path_extra.startswith('/'):
 
255
            raise ValueError(client_path_extra)
 
256
        from bzrlib.transport.chroot import ChrootServer
 
257
        if backing_transport_server is None:
 
258
            from bzrlib.transport.local import LocalURLServer
 
259
            backing_transport_server = LocalURLServer()
 
260
        self.chroot_server = ChrootServer(
 
261
            self.get_backing_transport(backing_transport_server))
 
262
        self.chroot_server.setUp()
 
263
        self.backing_transport = transport.get_transport(
 
264
            self.chroot_server.get_url())
 
265
        self.root_client_path = self.client_path_extra = client_path_extra
 
266
        self.start_background_thread(self.thread_name_suffix)
 
267
 
 
268
    def tearDown(self):
 
269
        self.stop_background_thread()
 
270
        self.chroot_server.tearDown()
 
271
 
 
272
    def get_url(self):
 
273
        url = super(SmartTCPServer_for_testing, self).get_url()
 
274
        return url[:-1] + self.client_path_extra
 
275
 
 
276
    def get_bogus_url(self):
 
277
        """Return a URL which will fail to connect"""
 
278
        return 'bzr://127.0.0.1:1/'
 
279
 
 
280
 
 
281
class ReadonlySmartTCPServer_for_testing(SmartTCPServer_for_testing):
 
282
    """Get a readonly server for testing."""
 
283
 
 
284
    def get_backing_transport(self, backing_transport_server):
 
285
        """Get a backing transport from a server we are decorating."""
 
286
        url = 'readonly+' + backing_transport_server.get_url()
 
287
        return transport.get_transport(url)
 
288
 
 
289
 
 
290
class SmartTCPServer_for_testing_v2_only(SmartTCPServer_for_testing):
 
291
    """A variation of SmartTCPServer_for_testing that limits the client to
 
292
    using RPCs in protocol v2 (i.e. bzr <= 1.5).
 
293
    """
 
294
 
 
295
    def get_url(self):
 
296
        url = super(SmartTCPServer_for_testing_v2_only, self).get_url()
 
297
        url = 'bzr-v2://' + url[len('bzr://'):]
 
298
        return url
 
299
 
 
300
 
 
301
class ReadonlySmartTCPServer_for_testing_v2_only(SmartTCPServer_for_testing_v2_only):
 
302
    """Get a readonly server for testing."""
 
303
 
 
304
    def get_backing_transport(self, backing_transport_server):
 
305
        """Get a backing transport from a server we are decorating."""
 
306
        url = 'readonly+' + backing_transport_server.get_url()
 
307
        return transport.get_transport(url)
 
308
 
 
309
 
 
310
def serve_bzr(transport, host=None, port=None, inet=False):
 
311
    from bzrlib import lockdir, ui
 
312
    from bzrlib.transport import get_transport
 
313
    from bzrlib.transport.chroot import ChrootServer
 
314
    chroot_server = ChrootServer(transport)
 
315
    chroot_server.setUp()
 
316
    t = get_transport(chroot_server.get_url())
 
317
    if inet:
 
318
        smart_server = medium.SmartServerPipeStreamMedium(
 
319
            sys.stdin, sys.stdout, transport)
 
320
    else:
 
321
        if host is None:
 
322
            host = medium.BZR_DEFAULT_INTERFACE
 
323
        if port is None:
 
324
            port = medium.BZR_DEFAULT_PORT
 
325
        smart_server = SmartTCPServer(
 
326
            transport, host=host, port=port)
 
327
        trace.note('listening on port: %s' % smart_server.port)
 
328
    # For the duration of this server, no UI output is permitted. note
 
329
    # that this may cause problems with blackbox tests. This should be
 
330
    # changed with care though, as we dont want to use bandwidth sending
 
331
    # progress over stderr to smart server clients!
 
332
    old_factory = ui.ui_factory
 
333
    old_lockdir_timeout = lockdir._DEFAULT_TIMEOUT_SECONDS
 
334
    try:
 
335
        ui.ui_factory = ui.SilentUIFactory()
 
336
        lockdir._DEFAULT_TIMEOUT_SECONDS = 0
 
337
        smart_server.serve()
 
338
    finally:
 
339
        ui.ui_factory = old_factory
 
340
        lockdir._DEFAULT_TIMEOUT_SECONDS = old_lockdir_timeout
 
341