/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-03-12 20:13:07 UTC
  • mfrom: (3267 +trunk)
  • mto: This revision was merged to the branch mainline in revision 3756.
  • Revision ID: andrew.bennetts@canonical.com-20080312201307-ngd5bynt2nvhnlb7
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
        """Construct a new server.
 
46
 
 
47
        To actually start it running, call either start_background_thread or
 
48
        serve.
 
49
 
 
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
        """
 
53
        # let connections timeout so that we get a chance to terminate
 
54
        # Keep a reference to the exceptions we want to catch because the socket
 
55
        # module's globals get set to None during interpreter shutdown.
 
56
        from socket import timeout as socket_timeout
 
57
        from socket import error as socket_error
 
58
        self._socket_error = socket_error
 
59
        self._socket_timeout = socket_timeout
 
60
        self._server_socket = socket.socket()
 
61
        self._server_socket.bind((host, port))
 
62
        self._sockname = self._server_socket.getsockname()
 
63
        self.port = self._sockname[1]
 
64
        self._server_socket.listen(1)
 
65
        self._server_socket.settimeout(1)
 
66
        self.backing_transport = backing_transport
 
67
        self._started = threading.Event()
 
68
        self._stopped = threading.Event()
 
69
 
 
70
    def serve(self):
 
71
        self._should_terminate = False
 
72
        # for hooks we are letting code know that a server has started (and
 
73
        # later stopped).
 
74
        # There are three interesting urls:
 
75
        # The URL the server can be contacted on. (e.g. bzr://host/)
 
76
        # The URL that a commit done on the same machine as the server will
 
77
        # have within the servers space. (e.g. file:///home/user/source)
 
78
        # The URL that will be given to other hooks in the same process -
 
79
        # the URL of the backing transport itself. (e.g. chroot+:///)
 
80
        # We need all three because:
 
81
        #  * other machines see the first
 
82
        #  * local commits on this machine should be able to be mapped to
 
83
        #    this server 
 
84
        #  * commits the server does itself need to be mapped across to this
 
85
        #    server.
 
86
        # The latter two urls are different aliases to the servers url,
 
87
        # so we group those in a list - as there might be more aliases 
 
88
        # in the future.
 
89
        backing_urls = [self.backing_transport.base]
 
90
        try:
 
91
            backing_urls.append(self.backing_transport.external_url())
 
92
        except errors.InProcessTransport:
 
93
            pass
 
94
        for hook in SmartTCPServer.hooks['server_started']:
 
95
            hook(backing_urls, self.get_url())
 
96
        self._started.set()
 
97
        try:
 
98
            try:
 
99
                while not self._should_terminate:
 
100
                    try:
 
101
                        conn, client_addr = self._server_socket.accept()
 
102
                    except self._socket_timeout:
 
103
                        # just check if we're asked to stop
 
104
                        pass
 
105
                    except self._socket_error, e:
 
106
                        # if the socket is closed by stop_background_thread
 
107
                        # we might get a EBADF here, any other socket errors
 
108
                        # should get logged.
 
109
                        if e.args[0] != errno.EBADF:
 
110
                            trace.warning("listening socket error: %s", e)
 
111
                    else:
 
112
                        self.serve_conn(conn)
 
113
            except KeyboardInterrupt:
 
114
                # dont log when CTRL-C'd.
 
115
                raise
 
116
            except Exception, e:
 
117
                trace.error("Unhandled smart server error.")
 
118
                trace.log_exception_quietly()
 
119
                raise
 
120
        finally:
 
121
            self._stopped.set()
 
122
            try:
 
123
                # ensure the server socket is closed.
 
124
                self._server_socket.close()
 
125
            except self._socket_error:
 
126
                # ignore errors on close
 
127
                pass
 
128
            for hook in SmartTCPServer.hooks['server_stopped']:
 
129
                hook(backing_urls, self.get_url())
 
130
 
 
131
    def get_url(self):
 
132
        """Return the url of the server"""
 
133
        return "bzr://%s:%d/" % self._sockname
 
134
 
 
135
    def serve_conn(self, conn):
 
136
        # For WIN32, where the timeout value from the listening socket
 
137
        # propogates to the newly accepted socket.
 
138
        conn.setblocking(True)
 
139
        conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
 
140
        handler = medium.SmartServerSocketStreamMedium(
 
141
            conn, self.backing_transport)
 
142
        connection_thread = threading.Thread(None, handler.serve, name='smart-server-child')
 
143
        connection_thread.setDaemon(True)
 
144
        connection_thread.start()
 
145
 
 
146
    def start_background_thread(self):
 
147
        self._started.clear()
 
148
        self._server_thread = threading.Thread(None,
 
149
                self.serve,
 
150
                name='server-' + self.get_url())
 
151
        self._server_thread.setDaemon(True)
 
152
        self._server_thread.start()
 
153
        self._started.wait()
 
154
 
 
155
    def stop_background_thread(self):
 
156
        self._stopped.clear()
 
157
        # tell the main loop to quit on the next iteration.
 
158
        self._should_terminate = True
 
159
        # close the socket - gives error to connections from here on in,
 
160
        # rather than a connection reset error to connections made during
 
161
        # the period between setting _should_terminate = True and 
 
162
        # the current request completing/aborting. It may also break out the
 
163
        # main loop if it was currently in accept() (on some platforms).
 
164
        try:
 
165
            self._server_socket.close()
 
166
        except self._socket_error:
 
167
            # ignore errors on close
 
168
            pass
 
169
        if not self._stopped.isSet():
 
170
            # server has not stopped (though it may be stopping)
 
171
            # its likely in accept(), so give it a connection
 
172
            temp_socket = socket.socket()
 
173
            temp_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
 
174
            if not temp_socket.connect_ex(self._sockname):
 
175
                # and close it immediately: we dont choose to send any requests.
 
176
                temp_socket.close()
 
177
        self._stopped.wait()
 
178
        self._server_thread.join()
 
179
 
 
180
 
 
181
class SmartServerHooks(Hooks):
 
182
    """Hooks for the smart server."""
 
183
 
 
184
    def __init__(self):
 
185
        """Create the default hooks.
 
186
 
 
187
        These are all empty initially, because by default nothing should get
 
188
        notified.
 
189
        """
 
190
        Hooks.__init__(self)
 
191
        # Introduced in 0.16:
 
192
        # invoked whenever the server starts serving a directory.
 
193
        # The api signature is (backing urls, public url).
 
194
        self['server_started'] = []
 
195
        # Introduced in 0.16:
 
196
        # invoked whenever the server stops serving a directory.
 
197
        # The api signature is (backing urls, public url).
 
198
        self['server_stopped'] = []
 
199
 
 
200
SmartTCPServer.hooks = SmartServerHooks()
 
201
 
 
202
 
 
203
class SmartTCPServer_for_testing(SmartTCPServer):
 
204
    """Server suitable for use by transport tests.
 
205
    
 
206
    This server is backed by the process's cwd.
 
207
    """
 
208
 
 
209
    def __init__(self):
 
210
        SmartTCPServer.__init__(self, None)
 
211
        
 
212
    def get_backing_transport(self, backing_transport_server):
 
213
        """Get a backing transport from a server we are decorating."""
 
214
        return transport.get_transport(backing_transport_server.get_url())
 
215
 
 
216
    def setUp(self, backing_transport_server=None):
 
217
        """Set up server for testing"""
 
218
        from bzrlib.transport.chroot import ChrootServer
 
219
        if backing_transport_server is None:
 
220
            from bzrlib.transport.local import LocalURLServer
 
221
            backing_transport_server = LocalURLServer()
 
222
        self.chroot_server = ChrootServer(
 
223
            self.get_backing_transport(backing_transport_server))
 
224
        self.chroot_server.setUp()
 
225
        self.backing_transport = transport.get_transport(
 
226
            self.chroot_server.get_url())
 
227
        self.start_background_thread()
 
228
 
 
229
    def tearDown(self):
 
230
        self.stop_background_thread()
 
231
        self.chroot_server.tearDown()
 
232
 
 
233
    def get_bogus_url(self):
 
234
        """Return a URL which will fail to connect"""
 
235
        return 'bzr://127.0.0.1:1/'
 
236
 
 
237
 
 
238
class ReadonlySmartTCPServer_for_testing(SmartTCPServer_for_testing):
 
239
    """Get a readonly server for testing."""
 
240
 
 
241
    def get_backing_transport(self, backing_transport_server):
 
242
        """Get a backing transport from a server we are decorating."""
 
243
        url = 'readonly+' + backing_transport_server.get_url()
 
244
        return transport.get_transport(url)
 
245