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
"""Construct a new server.
47
To actually start it running, call either start_background_thread or
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.
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()
71
self._should_terminate = False
72
# for hooks we are letting code know that a server has started (and
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
84
# * commits the server does itself need to be mapped across to this
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
89
backing_urls = [self.backing_transport.base]
91
backing_urls.append(self.backing_transport.external_url())
92
except errors.InProcessTransport:
94
for hook in SmartTCPServer.hooks['server_started']:
95
hook(backing_urls, self.get_url())
99
while not self._should_terminate:
101
conn, client_addr = self._server_socket.accept()
102
except self._socket_timeout:
103
# just check if we're asked to stop
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
109
if e.args[0] != errno.EBADF:
110
trace.warning("listening socket error: %s", e)
112
self.serve_conn(conn)
113
except KeyboardInterrupt:
114
# dont log when CTRL-C'd.
117
trace.error("Unhandled smart server error.")
118
trace.log_exception_quietly()
123
# ensure the server socket is closed.
124
self._server_socket.close()
125
except self._socket_error:
126
# ignore errors on close
128
for hook in SmartTCPServer.hooks['server_stopped']:
129
hook(backing_urls, self.get_url())
132
"""Return the url of the server"""
133
return "bzr://%s:%d/" % self._sockname
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()
146
def start_background_thread(self):
147
self._started.clear()
148
self._server_thread = threading.Thread(None,
150
name='server-' + self.get_url())
151
self._server_thread.setDaemon(True)
152
self._server_thread.start()
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).
165
self._server_socket.close()
166
except self._socket_error:
167
# ignore errors on close
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.
178
self._server_thread.join()
181
class SmartServerHooks(Hooks):
182
"""Hooks for the smart server."""
185
"""Create the default hooks.
187
These are all empty initially, because by default nothing should get
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'] = []
200
SmartTCPServer.hooks = SmartServerHooks()
203
class SmartTCPServer_for_testing(SmartTCPServer):
204
"""Server suitable for use by transport tests.
206
This server is backed by the process's cwd.
210
SmartTCPServer.__init__(self, None)
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())
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()
230
self.stop_background_thread()
231
self.chroot_server.tearDown()
233
def get_bogus_url(self):
234
"""Return a URL which will fail to connect"""
235
return 'bzr://127.0.0.1:1/'
238
class ReadonlySmartTCPServer_for_testing(SmartTCPServer_for_testing):
239
"""Get a readonly server for testing."""
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)