/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: Andrew Bennetts
  • Date: 2008-04-02 00:14:00 UTC
  • mfrom: (3324 +trunk)
  • mto: This revision was merged to the branch mainline in revision 3756.
  • Revision ID: andrew.bennetts@canonical.com-20080402001400-r1pqse38i03dl97w
Merge from bzr.dev.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006, 2007 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
"""Server for smart-server protocol."""
 
18
 
 
19
import errno
 
20
import socket
 
21
import threading
 
22
 
 
23
from bzrlib.hooks import Hooks
 
24
from bzrlib import (
 
25
    errors,
 
26
    trace,
 
27
    transport,
 
28
)
 
29
from bzrlib.lazy_import import lazy_import
 
30
lazy_import(globals(), """
 
31
from bzrlib.smart import medium
 
32
""")
 
33
 
 
34
 
 
35
class SmartTCPServer(object):
 
36
    """Listens on a TCP socket and accepts connections from smart clients.
 
37
 
 
38
    Each connection will be served by a SmartServerSocketStreamMedium running in
 
39
    a thread.
 
40
 
 
41
    hooks: An instance of SmartServerHooks.
 
42
    """
 
43
 
 
44
    def __init__(self, backing_transport, host='127.0.0.1', port=0,
 
45
                 root_client_path='/'):
 
46
        """Construct a new server.
 
47
 
 
48
        To actually start it running, call either start_background_thread or
 
49
        serve.
 
50
 
 
51
        :param backing_transport: The transport to serve.
 
52
        :param host: Name of the interface to listen on.
 
53
        :param port: TCP port to listen on, or 0 to allocate a transient port.
 
54
        :param root_client_path: The client path that will correspond to root
 
55
            of backing_transport.
 
56
        """
 
57
        # let connections timeout so that we get a chance to terminate
 
58
        # Keep a reference to the exceptions we want to catch because the socket
 
59
        # module's globals get set to None during interpreter shutdown.
 
60
        from socket import timeout as socket_timeout
 
61
        from socket import error as socket_error
 
62
        self._socket_error = socket_error
 
63
        self._socket_timeout = socket_timeout
 
64
        self._server_socket = socket.socket()
 
65
        self._server_socket.bind((host, port))
 
66
        self._sockname = self._server_socket.getsockname()
 
67
        self.port = self._sockname[1]
 
68
        self._server_socket.listen(1)
 
69
        self._server_socket.settimeout(1)
 
70
        self.backing_transport = backing_transport
 
71
        self._started = threading.Event()
 
72
        self._stopped = threading.Event()
 
73
        self.root_client_path = root_client_path
 
74
 
 
75
    def serve(self):
 
76
        self._should_terminate = False
 
77
        # for hooks we are letting code know that a server has started (and
 
78
        # later stopped).
 
79
        # There are three interesting urls:
 
80
        # The URL the server can be contacted on. (e.g. bzr://host/)
 
81
        # The URL that a commit done on the same machine as the server will
 
82
        # have within the servers space. (e.g. file:///home/user/source)
 
83
        # The URL that will be given to other hooks in the same process -
 
84
        # the URL of the backing transport itself. (e.g. chroot+:///)
 
85
        # We need all three because:
 
86
        #  * other machines see the first
 
87
        #  * local commits on this machine should be able to be mapped to
 
88
        #    this server 
 
89
        #  * commits the server does itself need to be mapped across to this
 
90
        #    server.
 
91
        # The latter two urls are different aliases to the servers url,
 
92
        # so we group those in a list - as there might be more aliases 
 
93
        # in the future.
 
94
        backing_urls = [self.backing_transport.base]
 
95
        try:
 
96
            backing_urls.append(self.backing_transport.external_url())
 
97
        except errors.InProcessTransport:
 
98
            pass
 
99
        for hook in SmartTCPServer.hooks['server_started']:
 
100
            hook(backing_urls, self.get_url())
 
101
        self._started.set()
 
102
        try:
 
103
            try:
 
104
                while not self._should_terminate:
 
105
                    try:
 
106
                        conn, client_addr = self._server_socket.accept()
 
107
                    except self._socket_timeout:
 
108
                        # just check if we're asked to stop
 
109
                        pass
 
110
                    except self._socket_error, e:
 
111
                        # if the socket is closed by stop_background_thread
 
112
                        # we might get a EBADF here, any other socket errors
 
113
                        # should get logged.
 
114
                        if e.args[0] != errno.EBADF:
 
115
                            trace.warning("listening socket error: %s", e)
 
116
                    else:
 
117
                        self.serve_conn(conn)
 
118
            except KeyboardInterrupt:
 
119
                # dont log when CTRL-C'd.
 
120
                raise
 
121
            except Exception, e:
 
122
                trace.error("Unhandled smart server error.")
 
123
                trace.log_exception_quietly()
 
124
                raise
 
125
        finally:
 
126
            self._stopped.set()
 
127
            try:
 
128
                # ensure the server socket is closed.
 
129
                self._server_socket.close()
 
130
            except self._socket_error:
 
131
                # ignore errors on close
 
132
                pass
 
133
            for hook in SmartTCPServer.hooks['server_stopped']:
 
134
                hook(backing_urls, self.get_url())
 
135
 
 
136
    def get_url(self):
 
137
        """Return the url of the server"""
 
138
        return "bzr://%s:%d/" % self._sockname
 
139
 
 
140
    def serve_conn(self, conn):
 
141
        # For WIN32, where the timeout value from the listening socket
 
142
        # propogates to the newly accepted socket.
 
143
        conn.setblocking(True)
 
144
        conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
 
145
        handler = medium.SmartServerSocketStreamMedium(
 
146
            conn, self.backing_transport, self.root_client_path)
 
147
        connection_thread = threading.Thread(None, handler.serve, name='smart-server-child')
 
148
        connection_thread.setDaemon(True)
 
149
        connection_thread.start()
 
150
 
 
151
    def start_background_thread(self):
 
152
        self._started.clear()
 
153
        self._server_thread = threading.Thread(None,
 
154
                self.serve,
 
155
                name='server-' + self.get_url())
 
156
        self._server_thread.setDaemon(True)
 
157
        self._server_thread.start()
 
158
        self._started.wait()
 
159
 
 
160
    def stop_background_thread(self):
 
161
        self._stopped.clear()
 
162
        # tell the main loop to quit on the next iteration.
 
163
        self._should_terminate = True
 
164
        # close the socket - gives error to connections from here on in,
 
165
        # rather than a connection reset error to connections made during
 
166
        # the period between setting _should_terminate = True and 
 
167
        # the current request completing/aborting. It may also break out the
 
168
        # main loop if it was currently in accept() (on some platforms).
 
169
        try:
 
170
            self._server_socket.close()
 
171
        except self._socket_error:
 
172
            # ignore errors on close
 
173
            pass
 
174
        if not self._stopped.isSet():
 
175
            # server has not stopped (though it may be stopping)
 
176
            # its likely in accept(), so give it a connection
 
177
            temp_socket = socket.socket()
 
178
            temp_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
 
179
            if not temp_socket.connect_ex(self._sockname):
 
180
                # and close it immediately: we dont choose to send any requests.
 
181
                temp_socket.close()
 
182
        self._stopped.wait()
 
183
        self._server_thread.join()
 
184
 
 
185
 
 
186
class SmartServerHooks(Hooks):
 
187
    """Hooks for the smart server."""
 
188
 
 
189
    def __init__(self):
 
190
        """Create the default hooks.
 
191
 
 
192
        These are all empty initially, because by default nothing should get
 
193
        notified.
 
194
        """
 
195
        Hooks.__init__(self)
 
196
        # Introduced in 0.16:
 
197
        # invoked whenever the server starts serving a directory.
 
198
        # The api signature is (backing urls, public url).
 
199
        self['server_started'] = []
 
200
        # Introduced in 0.16:
 
201
        # invoked whenever the server stops serving a directory.
 
202
        # The api signature is (backing urls, public url).
 
203
        self['server_stopped'] = []
 
204
 
 
205
SmartTCPServer.hooks = SmartServerHooks()
 
206
 
 
207
 
 
208
class SmartTCPServer_for_testing(SmartTCPServer):
 
209
    """Server suitable for use by transport tests.
 
210
    
 
211
    This server is backed by the process's cwd.
 
212
    """
 
213
 
 
214
    def __init__(self):
 
215
        SmartTCPServer.__init__(self, None)
 
216
        self.client_path_extra = None
 
217
        
 
218
    def get_backing_transport(self, backing_transport_server):
 
219
        """Get a backing transport from a server we are decorating."""
 
220
        return transport.get_transport(backing_transport_server.get_url())
 
221
 
 
222
    def setUp(self, backing_transport_server=None,
 
223
              client_path_extra='/extra/'):
 
224
        """Set up server for testing.
 
225
        
 
226
        :param backing_transport_server: backing server to use.  If not
 
227
            specified, a LocalURLServer at the current working directory will
 
228
            be used.
 
229
        :param client_path_extra: a path segment starting with '/' to append to
 
230
            the root URL for this server.  For instance, a value of '/foo/bar/'
 
231
            will mean the root of the backing transport will be published at a
 
232
            URL like `bzr://127.0.0.1:nnnn/foo/bar/`, rather than
 
233
            `bzr://127.0.0.1:nnnn/`.  Default value is `extra`, so that tests
 
234
            by default will fail unless they do the necessary path translation.
 
235
        """
 
236
        assert client_path_extra.startswith('/')
 
237
        from bzrlib.transport.chroot import ChrootServer
 
238
        if backing_transport_server is None:
 
239
            from bzrlib.transport.local import LocalURLServer
 
240
            backing_transport_server = LocalURLServer()
 
241
        self.chroot_server = ChrootServer(
 
242
            self.get_backing_transport(backing_transport_server))
 
243
        self.chroot_server.setUp()
 
244
        self.backing_transport = transport.get_transport(
 
245
            self.chroot_server.get_url())
 
246
        self.root_client_path = self.client_path_extra = client_path_extra
 
247
        self.start_background_thread()
 
248
 
 
249
    def tearDown(self):
 
250
        self.stop_background_thread()
 
251
        self.chroot_server.tearDown()
 
252
 
 
253
    def get_url(self):
 
254
        url = super(SmartTCPServer_for_testing, self).get_url()
 
255
        assert url.endswith('/')
 
256
        return url[:-1] + self.client_path_extra
 
257
 
 
258
    def get_bogus_url(self):
 
259
        """Return a URL which will fail to connect"""
 
260
        return 'bzr://127.0.0.1:1/'
 
261
 
 
262
 
 
263
class ReadonlySmartTCPServer_for_testing(SmartTCPServer_for_testing):
 
264
    """Get a readonly server for testing."""
 
265
 
 
266
    def get_backing_transport(self, backing_transport_server):
 
267
        """Get a backing transport from a server we are decorating."""
 
268
        url = 'readonly+' + backing_transport_server.get_url()
 
269
        return transport.get_transport(url)
 
270