/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: Martin Albisetti
  • Date: 2008-05-06 00:21:18 UTC
  • mto: (3431.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 3432.
  • Revision ID: argentina@gmail.com-20080506002118-7w9ywklw4khddf3g
Added spanish index

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