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