1
# Copyright (C) 2006, 2007, 2008 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."""
24
from bzrlib.hooks import Hooks
30
from bzrlib.smart.medium import SmartServerSocketStreamMedium
33
class SmartTCPServer(object):
34
"""Listens on a TCP socket and accepts connections from smart clients.
36
Each connection will be served by a SmartServerSocketStreamMedium running in
39
hooks: An instance of SmartServerHooks.
42
def __init__(self, backing_transport, host='127.0.0.1', port=0,
43
root_client_path='/'):
44
"""Construct a new server.
46
To actually start it running, call either start_background_thread or
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
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
addrs = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
63
socket.SOCK_STREAM, 0, socket.AI_PASSIVE)[0]
65
(family, socktype, proto, canonname, sockaddr) = addrs
67
self._server_socket = socket.socket(family, socktype, proto)
68
# SO_REUSERADDR has a different meaning on Windows
69
if sys.platform != 'win32':
70
self._server_socket.setsockopt(socket.SOL_SOCKET,
71
socket.SO_REUSEADDR, 1)
73
self._server_socket.bind(sockaddr)
74
except self._socket_error, message:
75
raise errors.CannotBindAddress(host, port, message)
76
self._sockname = self._server_socket.getsockname()
77
self.port = self._sockname[1]
78
self._server_socket.listen(1)
79
self._server_socket.settimeout(1)
80
self.backing_transport = backing_transport
81
self._started = threading.Event()
82
self._stopped = threading.Event()
83
self.root_client_path = root_client_path
85
def serve(self, thread_name_suffix=''):
86
self._should_terminate = False
87
# for hooks we are letting code know that a server has started (and
89
# There are three interesting urls:
90
# The URL the server can be contacted on. (e.g. bzr://host/)
91
# The URL that a commit done on the same machine as the server will
92
# have within the servers space. (e.g. file:///home/user/source)
93
# The URL that will be given to other hooks in the same process -
94
# the URL of the backing transport itself. (e.g. chroot+:///)
95
# We need all three because:
96
# * other machines see the first
97
# * local commits on this machine should be able to be mapped to
99
# * commits the server does itself need to be mapped across to this
101
# The latter two urls are different aliases to the servers url,
102
# so we group those in a list - as there might be more aliases
104
backing_urls = [self.backing_transport.base]
106
backing_urls.append(self.backing_transport.external_url())
107
except errors.InProcessTransport:
109
for hook in SmartTCPServer.hooks['server_started']:
110
hook(backing_urls, self.get_url())
114
while not self._should_terminate:
116
conn, client_addr = self._server_socket.accept()
117
except self._socket_timeout:
118
# just check if we're asked to stop
120
except self._socket_error, e:
121
# if the socket is closed by stop_background_thread
122
# we might get a EBADF here, any other socket errors
124
if e.args[0] != errno.EBADF:
125
trace.warning("listening socket error: %s", e)
127
self.serve_conn(conn, thread_name_suffix)
128
except KeyboardInterrupt:
129
# dont log when CTRL-C'd.
132
trace.error("Unhandled smart server error.")
133
trace.log_exception_quietly()
138
# ensure the server socket is closed.
139
self._server_socket.close()
140
except self._socket_error:
141
# ignore errors on close
143
for hook in SmartTCPServer.hooks['server_stopped']:
144
hook(backing_urls, self.get_url())
147
"""Return the url of the server"""
148
return "bzr://%s:%d/" % self._sockname
150
def serve_conn(self, conn, thread_name_suffix):
151
# For WIN32, where the timeout value from the listening socket
152
# propogates to the newly accepted socket.
153
conn.setblocking(True)
154
conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
155
handler = SmartServerSocketStreamMedium(
156
conn, self.backing_transport, self.root_client_path)
157
thread_name = 'smart-server-child' + thread_name_suffix
158
connection_thread = threading.Thread(
159
None, handler.serve, name=thread_name)
160
connection_thread.setDaemon(True)
161
connection_thread.start()
163
def start_background_thread(self, thread_name_suffix=''):
164
self._started.clear()
165
self._server_thread = threading.Thread(None,
166
self.serve, args=(thread_name_suffix,),
167
name='server-' + self.get_url())
168
self._server_thread.setDaemon(True)
169
self._server_thread.start()
172
def stop_background_thread(self):
173
self._stopped.clear()
174
# tell the main loop to quit on the next iteration.
175
self._should_terminate = True
176
# close the socket - gives error to connections from here on in,
177
# rather than a connection reset error to connections made during
178
# the period between setting _should_terminate = True and
179
# the current request completing/aborting. It may also break out the
180
# main loop if it was currently in accept() (on some platforms).
182
self._server_socket.close()
183
except self._socket_error:
184
# ignore errors on close
186
if not self._stopped.isSet():
187
# server has not stopped (though it may be stopping)
188
# its likely in accept(), so give it a connection
189
temp_socket = socket.socket()
190
temp_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
191
if not temp_socket.connect_ex(self._sockname):
192
# and close it immediately: we dont choose to send any requests.
195
self._server_thread.join()
198
class SmartServerHooks(Hooks):
199
"""Hooks for the smart server."""
202
"""Create the default hooks.
204
These are all empty initially, because by default nothing should get
208
# Introduced in 0.16:
209
# invoked whenever the server starts serving a directory.
210
# The api signature is (backing urls, public url).
211
self['server_started'] = []
212
# Introduced in 0.16:
213
# invoked whenever the server stops serving a directory.
214
# The api signature is (backing urls, public url).
215
self['server_stopped'] = []
217
SmartTCPServer.hooks = SmartServerHooks()
220
class SmartTCPServer_for_testing(SmartTCPServer):
221
"""Server suitable for use by transport tests.
223
This server is backed by the process's cwd.
226
def __init__(self, thread_name_suffix=''):
227
SmartTCPServer.__init__(self, None)
228
self.client_path_extra = None
229
self.thread_name_suffix = thread_name_suffix
231
def get_backing_transport(self, backing_transport_server):
232
"""Get a backing transport from a server we are decorating."""
233
return transport.get_transport(backing_transport_server.get_url())
235
def setUp(self, backing_transport_server=None,
236
client_path_extra='/extra/'):
237
"""Set up server for testing.
239
:param backing_transport_server: backing server to use. If not
240
specified, a LocalURLServer at the current working directory will
242
:param client_path_extra: a path segment starting with '/' to append to
243
the root URL for this server. For instance, a value of '/foo/bar/'
244
will mean the root of the backing transport will be published at a
245
URL like `bzr://127.0.0.1:nnnn/foo/bar/`, rather than
246
`bzr://127.0.0.1:nnnn/`. Default value is `extra`, so that tests
247
by default will fail unless they do the necessary path translation.
249
if not client_path_extra.startswith('/'):
250
raise ValueError(client_path_extra)
251
from bzrlib.transport.chroot import ChrootServer
252
if backing_transport_server is None:
253
from bzrlib.transport.local import LocalURLServer
254
backing_transport_server = LocalURLServer()
255
self.chroot_server = ChrootServer(
256
self.get_backing_transport(backing_transport_server))
257
self.chroot_server.setUp()
258
self.backing_transport = transport.get_transport(
259
self.chroot_server.get_url())
260
self.root_client_path = self.client_path_extra = client_path_extra
261
self.start_background_thread(self.thread_name_suffix)
264
self.stop_background_thread()
265
self.chroot_server.tearDown()
268
url = super(SmartTCPServer_for_testing, self).get_url()
269
return url[:-1] + self.client_path_extra
271
def get_bogus_url(self):
272
"""Return a URL which will fail to connect"""
273
return 'bzr://127.0.0.1:1/'
276
class ReadonlySmartTCPServer_for_testing(SmartTCPServer_for_testing):
277
"""Get a readonly server for testing."""
279
def get_backing_transport(self, backing_transport_server):
280
"""Get a backing transport from a server we are decorating."""
281
url = 'readonly+' + backing_transport_server.get_url()
282
return transport.get_transport(url)
285
class SmartTCPServer_for_testing_v2_only(SmartTCPServer_for_testing):
286
"""A variation of SmartTCPServer_for_testing that limits the client to
287
using RPCs in protocol v2 (i.e. bzr <= 1.5).
291
url = super(SmartTCPServer_for_testing_v2_only, self).get_url()
292
url = 'bzr-v2://' + url[len('bzr://'):]
296
class ReadonlySmartTCPServer_for_testing_v2_only(SmartTCPServer_for_testing_v2_only):
297
"""Get a readonly server for testing."""
299
def get_backing_transport(self, backing_transport_server):
300
"""Get a backing transport from a server we are decorating."""
301
url = 'readonly+' + backing_transport_server.get_url()
302
return transport.get_transport(url)