1
# Copyright (C) 2006, 2007 Canonical Ltd
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.
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.
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
17
"""Server for smart-server protocol."""
23
from bzrlib.hooks import Hooks
29
from bzrlib.smart.medium import SmartServerSocketStreamMedium
32
class SmartTCPServer(object):
33
"""Listens on a TCP socket and accepts connections from smart clients.
35
Each connection will be served by a SmartServerSocketStreamMedium running in
38
hooks: An instance of SmartServerHooks.
41
def __init__(self, backing_transport, host='127.0.0.1', port=0):
42
"""Construct a new server.
44
To actually start it running, call either start_background_thread or
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.
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
self.root_client_path = '/'
69
self._should_terminate = False
70
# for hooks we are letting code know that a server has started (and
72
# There are three interesting urls:
73
# The URL the server can be contacted on. (e.g. bzr://host/)
74
# The URL that a commit done on the same machine as the server will
75
# have within the servers space. (e.g. file:///home/user/source)
76
# The URL that will be given to other hooks in the same process -
77
# the URL of the backing transport itself. (e.g. chroot+:///)
78
# We need all three because:
79
# * other machines see the first
80
# * local commits on this machine should be able to be mapped to
82
# * commits the server does itself need to be mapped across to this
84
# The latter two urls are different aliases to the servers url,
85
# so we group those in a list - as there might be more aliases
87
backing_urls = [self.backing_transport.base]
89
backing_urls.append(self.backing_transport.external_url())
90
except errors.InProcessTransport:
92
for hook in SmartTCPServer.hooks['server_started']:
93
hook(backing_urls, self.get_url())
97
while not self._should_terminate:
99
conn, client_addr = self._server_socket.accept()
100
except self._socket_timeout:
101
# just check if we're asked to stop
103
except self._socket_error, e:
104
# if the socket is closed by stop_background_thread
105
# we might get a EBADF here, any other socket errors
107
if e.args[0] != errno.EBADF:
108
trace.warning("listening socket error: %s", e)
110
self.serve_conn(conn)
111
except KeyboardInterrupt:
112
# dont log when CTRL-C'd.
115
trace.error("Unhandled smart server error.")
116
trace.log_exception_quietly()
121
# ensure the server socket is closed.
122
self._server_socket.close()
123
except self._socket_error:
124
# ignore errors on close
126
for hook in SmartTCPServer.hooks['server_stopped']:
127
hook(backing_urls, self.get_url())
130
"""Return the url of the server"""
131
return "bzr://%s:%d/" % self._sockname
133
def serve_conn(self, conn):
134
# For WIN32, where the timeout value from the listening socket
135
# propogates to the newly accepted socket.
136
conn.setblocking(True)
137
conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
138
handler = SmartServerSocketStreamMedium(
139
conn, self.backing_transport, self.root_client_path)
140
connection_thread = threading.Thread(None, handler.serve, name='smart-server-child')
141
connection_thread.setDaemon(True)
142
connection_thread.start()
144
def start_background_thread(self):
145
self._started.clear()
146
self._server_thread = threading.Thread(None,
148
name='server-' + self.get_url())
149
self._server_thread.setDaemon(True)
150
self._server_thread.start()
153
def stop_background_thread(self):
154
self._stopped.clear()
155
# tell the main loop to quit on the next iteration.
156
self._should_terminate = True
157
# close the socket - gives error to connections from here on in,
158
# rather than a connection reset error to connections made during
159
# the period between setting _should_terminate = True and
160
# the current request completing/aborting. It may also break out the
161
# main loop if it was currently in accept() (on some platforms).
163
self._server_socket.close()
164
except self._socket_error:
165
# ignore errors on close
167
if not self._stopped.isSet():
168
# server has not stopped (though it may be stopping)
169
# its likely in accept(), so give it a connection
170
temp_socket = socket.socket()
171
temp_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
172
if not temp_socket.connect_ex(self._sockname):
173
# and close it immediately: we dont choose to send any requests.
176
self._server_thread.join()
179
class SmartServerHooks(Hooks):
180
"""Hooks for the smart server."""
183
"""Create the default hooks.
185
These are all empty initially, because by default nothing should get
189
# Introduced in 0.16:
190
# invoked whenever the server starts serving a directory.
191
# The api signature is (backing urls, public url).
192
self['server_started'] = []
193
# Introduced in 0.16:
194
# invoked whenever the server stops serving a directory.
195
# The api signature is (backing urls, public url).
196
self['server_stopped'] = []
198
SmartTCPServer.hooks = SmartServerHooks()
201
class SmartTCPServer_for_testing(SmartTCPServer):
202
"""Server suitable for use by transport tests.
204
This server is backed by the process's cwd.
208
SmartTCPServer.__init__(self, None)
209
self.client_path_extra = None
211
def get_backing_transport(self, backing_transport_server):
212
"""Get a backing transport from a server we are decorating."""
213
return transport.get_transport(backing_transport_server.get_url())
215
def setUp(self, backing_transport_server=None,
216
client_path_extra='/extra/'):
217
"""Set up server for testing.
219
:param backing_transport_server: backing server to use. If not
220
specified, a LocalURLServer at the current working directory will
222
:param client_path_extra: a path segment starting with '/' to append to
223
the root URL for this server. For instance, a value of '/foo/bar/'
224
will mean the root of the backing transport will be published at a
225
URL like `bzr://127.0.0.1:nnnn/foo/bar/`, rather than
226
`bzr://127.0.0.1:nnnn/`. Default value is `extra`, so that tests
227
by default will fail unless they do the necessary path translation.
229
assert client_path_extra.startswith('/')
230
from bzrlib.transport.chroot import ChrootServer
231
if backing_transport_server is None:
232
from bzrlib.transport.local import LocalURLServer
233
backing_transport_server = LocalURLServer()
234
self.chroot_server = ChrootServer(
235
self.get_backing_transport(backing_transport_server))
236
self.chroot_server.setUp()
237
self.backing_transport = transport.get_transport(
238
self.chroot_server.get_url())
239
self.root_client_path = self.client_path_extra = client_path_extra
240
self.start_background_thread()
243
self.stop_background_thread()
244
self.chroot_server.tearDown()
247
url = super(SmartTCPServer_for_testing, self).get_url()
248
assert url.endswith('/')
249
return url[:-1] + self.client_path_extra
251
def get_bogus_url(self):
252
"""Return a URL which will fail to connect"""
253
return 'bzr://127.0.0.1:1/'
256
class ReadonlySmartTCPServer_for_testing(SmartTCPServer_for_testing):
257
"""Get a readonly server for testing."""
259
def get_backing_transport(self, backing_transport_server):
260
"""Get a backing transport from a server we are decorating."""
261
url = 'readonly+' + backing_transport_server.get_url()
262
return transport.get_transport(url)