13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
17
"""Server for smart-server protocol."""
24
from bzrlib.hooks import HookPoint, Hooks
23
from bzrlib.hooks import Hooks
25
24
from bzrlib import (
30
from bzrlib.lazy_import import lazy_import
31
lazy_import(globals(), """
32
from bzrlib.smart import medium
29
from bzrlib.smart.medium import SmartServerSocketStreamMedium
36
32
class SmartTCPServer(object):
42
38
hooks: An instance of SmartServerHooks.
45
def __init__(self, backing_transport, host='127.0.0.1', port=0,
46
root_client_path='/'):
41
def __init__(self, backing_transport, host='127.0.0.1', port=0):
47
42
"""Construct a new server.
49
44
To actually start it running, call either start_background_thread or
52
:param backing_transport: The transport to serve.
53
47
:param host: Name of the interface to listen on.
54
48
:param port: TCP port to listen on, or 0 to allocate a transient port.
55
:param root_client_path: The client path that will correspond to root
58
50
# let connections timeout so that we get a chance to terminate
59
51
# Keep a reference to the exceptions we want to catch because the socket
62
54
from socket import error as socket_error
63
55
self._socket_error = socket_error
64
56
self._socket_timeout = socket_timeout
65
addrs = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
66
socket.SOCK_STREAM, 0, socket.AI_PASSIVE)[0]
68
(family, socktype, proto, canonname, sockaddr) = addrs
70
self._server_socket = socket.socket(family, socktype, proto)
71
# SO_REUSERADDR has a different meaning on Windows
72
if sys.platform != 'win32':
73
self._server_socket.setsockopt(socket.SOL_SOCKET,
74
socket.SO_REUSEADDR, 1)
76
self._server_socket.bind(sockaddr)
77
except self._socket_error, message:
78
raise errors.CannotBindAddress(host, port, message)
57
self._server_socket = socket.socket()
58
self._server_socket.bind((host, port))
79
59
self._sockname = self._server_socket.getsockname()
80
60
self.port = self._sockname[1]
81
61
self._server_socket.listen(1)
152
129
"""Return the url of the server"""
153
130
return "bzr://%s:%d/" % self._sockname
155
def serve_conn(self, conn, thread_name_suffix):
132
def serve_conn(self, conn):
156
133
# For WIN32, where the timeout value from the listening socket
157
# propagates to the newly accepted socket.
134
# propogates to the newly accepted socket.
158
135
conn.setblocking(True)
159
136
conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
160
handler = medium.SmartServerSocketStreamMedium(
161
conn, self.backing_transport, self.root_client_path)
162
thread_name = 'smart-server-child' + thread_name_suffix
163
connection_thread = threading.Thread(
164
None, handler.serve, name=thread_name)
137
handler = SmartServerSocketStreamMedium(conn, self.backing_transport)
138
connection_thread = threading.Thread(None, handler.serve, name='smart-server-child')
165
139
connection_thread.setDaemon(True)
166
140
connection_thread.start()
168
def start_background_thread(self, thread_name_suffix=''):
142
def start_background_thread(self):
169
143
self._started.clear()
170
144
self._server_thread = threading.Thread(None,
171
self.serve, args=(thread_name_suffix,),
172
146
name='server-' + self.get_url())
173
147
self._server_thread.setDaemon(True)
174
148
self._server_thread.start()
212
186
Hooks.__init__(self)
213
self.create_hook(HookPoint('server_started',
214
"Called by the bzr server when it starts serving a directory. "
215
"server_started is called with (backing urls, public url), "
216
"where backing_url is a list of URLs giving the "
217
"server-specific directory locations, and public_url is the "
218
"public URL for the directory being served.", (0, 16), None))
219
self.create_hook(HookPoint('server_started_ex',
220
"Called by the bzr server when it starts serving a directory. "
221
"server_started is called with (backing_urls, server_obj).",
223
self.create_hook(HookPoint('server_stopped',
224
"Called by the bzr server when it stops serving a directory. "
225
"server_stopped is called with the same parameters as the "
226
"server_started hook: (backing_urls, public_url).", (0, 16), None))
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'] = []
228
196
SmartTCPServer.hooks = SmartServerHooks()
231
199
class SmartTCPServer_for_testing(SmartTCPServer):
232
200
"""Server suitable for use by transport tests.
234
202
This server is backed by the process's cwd.
237
def __init__(self, thread_name_suffix=''):
238
206
SmartTCPServer.__init__(self, None)
239
self.client_path_extra = None
240
self.thread_name_suffix = thread_name_suffix
242
208
def get_backing_transport(self, backing_transport_server):
243
209
"""Get a backing transport from a server we are decorating."""
244
210
return transport.get_transport(backing_transport_server.get_url())
246
def setUp(self, backing_transport_server=None,
247
client_path_extra='/extra/'):
248
"""Set up server for testing.
250
:param backing_transport_server: backing server to use. If not
251
specified, a LocalURLServer at the current working directory will
253
:param client_path_extra: a path segment starting with '/' to append to
254
the root URL for this server. For instance, a value of '/foo/bar/'
255
will mean the root of the backing transport will be published at a
256
URL like `bzr://127.0.0.1:nnnn/foo/bar/`, rather than
257
`bzr://127.0.0.1:nnnn/`. Default value is `extra`, so that tests
258
by default will fail unless they do the necessary path translation.
260
if not client_path_extra.startswith('/'):
261
raise ValueError(client_path_extra)
212
def setUp(self, backing_transport_server=None):
213
"""Set up server for testing"""
262
214
from bzrlib.transport.chroot import ChrootServer
263
215
if backing_transport_server is None:
264
216
from bzrlib.transport.local import LocalURLServer
268
220
self.chroot_server.setUp()
269
221
self.backing_transport = transport.get_transport(
270
222
self.chroot_server.get_url())
271
self.root_client_path = self.client_path_extra = client_path_extra
272
self.start_background_thread(self.thread_name_suffix)
223
self.start_background_thread()
274
225
def tearDown(self):
275
226
self.stop_background_thread()
276
227
self.chroot_server.tearDown()
279
url = super(SmartTCPServer_for_testing, self).get_url()
280
return url[:-1] + self.client_path_extra
282
229
def get_bogus_url(self):
283
230
"""Return a URL which will fail to connect"""
284
231
return 'bzr://127.0.0.1:1/'
292
239
url = 'readonly+' + backing_transport_server.get_url()
293
240
return transport.get_transport(url)
296
class SmartTCPServer_for_testing_v2_only(SmartTCPServer_for_testing):
297
"""A variation of SmartTCPServer_for_testing that limits the client to
298
using RPCs in protocol v2 (i.e. bzr <= 1.5).
302
url = super(SmartTCPServer_for_testing_v2_only, self).get_url()
303
url = 'bzr-v2://' + url[len('bzr://'):]
307
class ReadonlySmartTCPServer_for_testing_v2_only(SmartTCPServer_for_testing_v2_only):
308
"""Get a readonly server for testing."""
310
def get_backing_transport(self, backing_transport_server):
311
"""Get a backing transport from a server we are decorating."""
312
url = 'readonly+' + backing_transport_server.get_url()
313
return transport.get_transport(url)
316
def serve_bzr(transport, host=None, port=None, inet=False):
317
from bzrlib import lockdir, ui
318
from bzrlib.transport import get_transport
319
from bzrlib.transport.chroot import ChrootServer
320
chroot_server = ChrootServer(transport)
321
chroot_server.setUp()
322
transport = get_transport(chroot_server.get_url())
324
smart_server = medium.SmartServerPipeStreamMedium(
325
sys.stdin, sys.stdout, transport)
328
host = medium.BZR_DEFAULT_INTERFACE
330
port = medium.BZR_DEFAULT_PORT
331
smart_server = SmartTCPServer(transport, host=host, port=port)
332
trace.note('listening on port: %s' % smart_server.port)
333
# For the duration of this server, no UI output is permitted. note
334
# that this may cause problems with blackbox tests. This should be
335
# changed with care though, as we dont want to use bandwidth sending
336
# progress over stderr to smart server clients!
337
old_factory = ui.ui_factory
338
old_lockdir_timeout = lockdir._DEFAULT_TIMEOUT_SECONDS
340
ui.ui_factory = ui.SilentUIFactory()
341
lockdir._DEFAULT_TIMEOUT_SECONDS = 0
344
ui.ui_factory = old_factory
345
lockdir._DEFAULT_TIMEOUT_SECONDS = old_lockdir_timeout