~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: 2009-04-09 20:23:07 UTC
  • mfrom: (4265.1.4 bbc-merge)
  • Revision ID: pqm@pqm.ubuntu.com-20090409202307-n0depb16qepoe21o
(jam) Change _fetch_uses_deltas = False for CHK repos until we can
        write a better fix.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006, 2007 Canonical Ltd
 
1
# Copyright (C) 2006, 2007, 2008 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
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
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
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
"""Server for smart-server protocol."""
18
18
 
19
19
import errno
20
20
import socket
21
 
import os
 
21
import sys
22
22
import threading
23
23
 
24
 
from bzrlib.hooks import Hooks
25
 
from bzrlib.smart import medium
 
24
from bzrlib.hooks import HookPoint, Hooks
26
25
from bzrlib import (
 
26
    errors,
27
27
    trace,
28
28
    transport,
29
 
    urlutils,
30
29
)
31
 
from bzrlib.smart.medium import SmartServerSocketStreamMedium
 
30
from bzrlib.lazy_import import lazy_import
 
31
lazy_import(globals(), """
 
32
from bzrlib.smart import medium
 
33
""")
32
34
 
33
35
 
34
36
class SmartTCPServer(object):
35
 
    """Listens on a TCP socket and accepts connections from smart clients
 
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.
36
41
 
37
42
    hooks: An instance of SmartServerHooks.
38
43
    """
39
44
 
40
 
    def __init__(self, backing_transport, host='127.0.0.1', port=0):
 
45
    def __init__(self, backing_transport, host='127.0.0.1', port=0,
 
46
                 root_client_path='/'):
41
47
        """Construct a new server.
42
48
 
43
49
        To actually start it running, call either start_background_thread or
44
50
        serve.
45
51
 
 
52
        :param backing_transport: The transport to serve.
46
53
        :param host: Name of the interface to listen on.
47
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.
48
57
        """
49
58
        # let connections timeout so that we get a chance to terminate
50
59
        # Keep a reference to the exceptions we want to catch because the socket
53
62
        from socket import error as socket_error
54
63
        self._socket_error = socket_error
55
64
        self._socket_timeout = socket_timeout
56
 
        self._server_socket = socket.socket()
57
 
        self._server_socket.bind((host, port))
 
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)
58
79
        self._sockname = self._server_socket.getsockname()
59
80
        self.port = self._sockname[1]
60
81
        self._server_socket.listen(1)
62
83
        self.backing_transport = backing_transport
63
84
        self._started = threading.Event()
64
85
        self._stopped = threading.Event()
 
86
        self.root_client_path = root_client_path
65
87
 
66
 
    def serve(self):
 
88
    def serve(self, thread_name_suffix=''):
67
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
68
112
        for hook in SmartTCPServer.hooks['server_started']:
69
 
            hook(self.backing_transport.base, self.get_url())
 
113
            hook(backing_urls, self.get_url())
70
114
        self._started.set()
71
115
        try:
72
116
            try:
83
127
                        if e.args[0] != errno.EBADF:
84
128
                            trace.warning("listening socket error: %s", e)
85
129
                    else:
86
 
                        self.serve_conn(conn)
 
130
                        self.serve_conn(conn, thread_name_suffix)
87
131
            except KeyboardInterrupt:
88
132
                # dont log when CTRL-C'd.
89
133
                raise
100
144
                # ignore errors on close
101
145
                pass
102
146
            for hook in SmartTCPServer.hooks['server_stopped']:
103
 
                hook(self.backing_transport.base, self.get_url())
 
147
                hook(backing_urls, self.get_url())
104
148
 
105
149
    def get_url(self):
106
150
        """Return the url of the server"""
107
151
        return "bzr://%s:%d/" % self._sockname
108
152
 
109
 
    def serve_conn(self, conn):
 
153
    def serve_conn(self, conn, thread_name_suffix):
110
154
        # For WIN32, where the timeout value from the listening socket
111
 
        # propogates to the newly accepted socket.
 
155
        # propagates to the newly accepted socket.
112
156
        conn.setblocking(True)
113
157
        conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
114
 
        handler = SmartServerSocketStreamMedium(conn, self.backing_transport)
115
 
        connection_thread = threading.Thread(None, handler.serve, name='smart-server-child')
 
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)
116
163
        connection_thread.setDaemon(True)
117
164
        connection_thread.start()
118
165
 
119
 
    def start_background_thread(self):
 
166
    def start_background_thread(self, thread_name_suffix=''):
120
167
        self._started.clear()
121
168
        self._server_thread = threading.Thread(None,
122
 
                self.serve,
 
169
                self.serve, args=(thread_name_suffix,),
123
170
                name='server-' + self.get_url())
124
171
        self._server_thread.setDaemon(True)
125
172
        self._server_thread.start()
131
178
        self._should_terminate = True
132
179
        # close the socket - gives error to connections from here on in,
133
180
        # rather than a connection reset error to connections made during
134
 
        # the period between setting _should_terminate = True and 
 
181
        # the period between setting _should_terminate = True and
135
182
        # the current request completing/aborting. It may also break out the
136
183
        # main loop if it was currently in accept() (on some platforms).
137
184
        try:
161
208
        notified.
162
209
        """
163
210
        Hooks.__init__(self)
164
 
        # Introduced in 0.16:
165
 
        # invoked whenever the server starts serving a directory.
166
 
        # The api signature is (backing url, public url).
167
 
        self['server_started'] = []
168
 
        # Introduced in 0.16:
169
 
        # invoked whenever the server stops serving a directory.
170
 
        # The api signature is (backing url, public url).
171
 
        self['server_stopped'] = []
 
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))
172
221
 
173
222
SmartTCPServer.hooks = SmartServerHooks()
174
223
 
175
224
 
176
225
class SmartTCPServer_for_testing(SmartTCPServer):
177
226
    """Server suitable for use by transport tests.
178
 
    
 
227
 
179
228
    This server is backed by the process's cwd.
180
229
    """
181
230
 
182
 
    def __init__(self):
183
 
        self._homedir = urlutils.local_path_to_url(os.getcwd())[7:]
184
 
        # The server is set up by default like for ssh access: the client
185
 
        # passes filesystem-absolute paths; therefore the server must look
186
 
        # them up relative to the root directory.  it might be better to act
187
 
        # a public server and have the server rewrite paths into the test
188
 
        # directory.
189
 
        SmartTCPServer.__init__(self,
190
 
            transport.get_transport(urlutils.local_path_to_url('/')))
191
 
        
 
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
 
192
236
    def get_backing_transport(self, backing_transport_server):
193
237
        """Get a backing transport from a server we are decorating."""
194
238
        return transport.get_transport(backing_transport_server.get_url())
195
239
 
196
 
    def setUp(self, backing_transport_server=None):
197
 
        """Set up server for testing"""
198
 
        from bzrlib.transport.chroot import TestingChrootServer
 
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
199
257
        if backing_transport_server is None:
200
258
            from bzrlib.transport.local import LocalURLServer
201
259
            backing_transport_server = LocalURLServer()
202
 
        self.chroot_server = TestingChrootServer()
203
 
        self.chroot_server.setUp(backing_transport_server)
 
260
        self.chroot_server = ChrootServer(
 
261
            self.get_backing_transport(backing_transport_server))
 
262
        self.chroot_server.setUp()
204
263
        self.backing_transport = transport.get_transport(
205
264
            self.chroot_server.get_url())
206
 
        self.start_background_thread()
 
265
        self.root_client_path = self.client_path_extra = client_path_extra
 
266
        self.start_background_thread(self.thread_name_suffix)
207
267
 
208
268
    def tearDown(self):
209
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
210
275
 
211
276
    def get_bogus_url(self):
212
277
        """Return a URL which will fail to connect"""
213
278
        return 'bzr://127.0.0.1:1/'
214
279
 
215
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