/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: Robert Collins
  • Date: 2007-08-08 02:57:22 UTC
  • mto: This revision was merged to the branch mainline in revision 2687.
  • Revision ID: robertc@robertcollins.net-20070808025722-26wvnolkzmnse7s1
* The ``bzrlib.pack`` interface has changed to use tuples of bytestrings
  rather than just bytestrings, making it easier to represent multiple
  element names. As this interface was not used by any internal facilities
  since it was introduced in 0.18 no API compatibility is being preserved.
  The serialised form of these packs is identical with 0.18 when a single
  element tuple is in use. (Robert Collins)

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