37
from ...branch import Branch
38
from ...controldir import ControlDir
39
from ...bzr.smart import client, medium
40
from ...bzr.smart.server import (
36
from brzlib.branch import Branch
37
from brzlib.controldir import ControlDir
38
from brzlib.smart import client, medium
39
from brzlib.smart.server import (
43
from brzlib.tests import (
45
44
TestCaseWithMemoryTransport,
46
45
TestCaseWithTransport,
48
from ...transport import remote
47
from brzlib.transport import remote
51
50
class TestBzrServeBase(TestCaseWithTransport):
53
52
def run_bzr_serve_then_func(self, serve_args, retcode=0, func=None,
54
53
*func_args, **func_kwargs):
55
"""Run 'brz serve', and run the given func in a thread once the server
54
"""Run 'bzr serve', and run the given func in a thread once the server
58
57
When 'func' terminates, the server will be terminated too.
71
70
if func is not None:
73
72
func(*func_args, **func_kwargs)
74
except Exception as e:
75
74
# Log errors to make some test failures a little less
77
76
trace.mutter('func broke: %r', e)
79
78
# Then stop the server
80
79
trace.mutter('interrupting...')
80
thread.interrupt_main()
82
81
# When the hook is fired, it just starts ``on_server_start_thread`` and
85
83
def on_server_start(backing_urls, tcp_server):
86
84
t = threading.Thread(
87
85
target=on_server_start_thread, args=(tcp_server,))
90
88
SmartTCPServer.hooks.install_named_hook(
91
89
'server_started_ex', on_server_start,
92
90
'run_bzr_serve_then_func hook')
93
# It seems interrupt_main() will not raise KeyboardInterrupt
91
# It seesm thread.interrupt_main() will not raise KeyboardInterrupt
94
92
# until after socket.accept returns. So we set the timeout low to make
96
94
self.overrideAttr(SmartTCPServer, '_ACCEPT_TIMEOUT', 0.1)
99
97
out, err = self.run_bzr(['serve'] + list(serve_args),
101
except KeyboardInterrupt as e:
102
return (self._last_cmd_stdout.getvalue(),
103
self._last_cmd_stderr.getvalue())
99
except KeyboardInterrupt, e:
142
139
# Hide stdin from the subprocess module, so it won't fail to close it.
143
140
process.stdin = None
144
141
result = self.finish_bzr_subprocess(process)
145
self.assertEqual(b'', result[0])
146
self.assertEqual(b'', result[1])
142
self.assertEqual('', result[0])
143
self.assertEqual('', result[1])
148
145
def assertServerFinishesCleanly(self, process):
149
"""Shutdown the brz serve instance process looking for errors."""
146
"""Shutdown the bzr serve instance process looking for errors."""
150
147
# Shutdown the server
151
148
result = self.finish_bzr_subprocess(process, retcode=3,
152
149
send_signal=signal.SIGINT)
153
self.assertEqual(b'', result[0])
154
self.assertEqual(b'brz: interrupted\n', result[1])
150
self.assertEqual('', result[0])
151
self.assertEqual('brz: interrupted\n', result[1])
156
153
def make_read_requests(self, branch):
157
154
"""Do some read only requests."""
158
with branch.lock_read():
159
157
branch.repository.all_revision_ids()
160
158
self.assertEqual(_mod_revision.NULL_REVISION,
161
159
_mod_revision.ensure_null(branch.last_revision()))
163
163
def start_server_inet(self, extra_options=()):
164
"""Start a brz server subprocess using the --inet option.
164
"""Start a bzr server subprocess using the --inet option.
166
166
:param extra_options: extra options to give the server.
167
:return: a tuple with the brz process handle for passing to
167
:return: a tuple with the bzr process handle for passing to
168
168
finish_bzr_subprocess, a client for the server, and a transport.
170
170
# Serve from the current directory
183
183
return process, transport
185
185
def start_server_port(self, extra_options=()):
186
"""Start a brz server subprocess.
186
"""Start a bzr server subprocess.
188
188
:param extra_options: extra options to give the server.
189
:return: a tuple with the brz process handle for passing to
189
:return: a tuple with the bzr process handle for passing to
190
190
finish_bzr_subprocess, and the base url for the server.
192
192
# Serve from the current directory
194
194
args.extend(extra_options)
195
195
process = self.start_bzr_subprocess(args, skip_if_plan_to_signal=True)
196
196
port_line = process.stderr.readline()
197
prefix = b'listening on port: '
197
prefix = 'listening on port: '
198
198
self.assertStartsWith(port_line, prefix)
199
199
port = int(port_line[len(prefix):])
200
200
url = 'bzr://localhost:%d/' % port
209
209
self.assertEqual('', err)
211
211
def test_bzr_serve_inet_readonly(self):
212
"""brz server should provide a read only filesystem by default."""
212
"""bzr server should provide a read only filesystem by default."""
213
213
process, transport = self.start_server_inet()
214
214
self.assertRaises(errors.TransportNotPossible, transport.mkdir, 'adir')
215
215
self.assertInetServerShutsdownCleanly(process)
227
227
self.assertInetServerShutsdownCleanly(process)
229
229
def test_bzr_serve_port_readonly(self):
230
"""brz server should provide a read only filesystem by default."""
230
"""bzr server should provide a read only filesystem by default."""
231
231
process, url = self.start_server_port()
232
232
t = transport.get_transport_from_url(url)
233
233
self.assertRaises(errors.TransportNotPossible, t.mkdir, 'adir')
260
260
# This is a smoke test that the server doesn't crash when run with
261
261
# -Dhpss, and does drop some hpss logging to the file.
262
262
self.make_branch('.')
263
log_fname = self.test_dir + '/server.log'
264
self.overrideEnv('BRZ_LOG', log_fname)
263
log_fname = os.getcwd() + '/server.log'
264
self.overrideEnv('BZR_LOG', log_fname)
265
265
process, transport = self.start_server_inet(['-Dhpss'])
266
266
branch = ControlDir.open_from_transport(transport).open_branch()
267
267
self.make_read_requests(branch)
269
269
f = open(log_fname, 'rb')
270
270
content = f.read()
272
self.assertContainsRe(content, br'hpss request: \[[0-9-]+\]')
272
self.assertContainsRe(content, r'hpss request: \[[0-9-]+\]')
274
274
def test_bzr_serve_supports_configurable_timeout(self):
275
275
gs = config.GlobalStack()
277
277
# Save the config as the subprocess will use it
279
279
process, url = self.start_server_port()
280
self.build_tree_contents([('a_file', b'contents\n')])
280
self.build_tree_contents([('a_file', 'contents\n')])
281
281
# We can connect and issue a request
282
282
t = transport.get_transport_from_url(url)
283
self.assertEqual(b'contents\n', t.get_bytes('a_file'))
283
self.assertEqual('contents\n', t.get_bytes('a_file'))
284
284
# However, if we just wait for more content from the server, it will
285
285
# eventually disconnect us.
286
286
m = t.get_smart_medium()
288
288
# Now, we wait for timeout to trigger
289
289
err = process.stderr.readline()
290
290
self.assertEqual(
291
b'Connection Timeout: disconnecting client after 0.2 seconds\n',
291
'Connection Timeout: disconnecting client after 0.2 seconds\n',
293
293
self.assertServerFinishesCleanly(process)
295
295
def test_bzr_serve_supports_client_timeout(self):
296
296
process, url = self.start_server_port(['--client-timeout=0.1'])
297
self.build_tree_contents([('a_file', b'contents\n')])
297
self.build_tree_contents([('a_file', 'contents\n')])
298
298
# We can connect and issue a request
299
299
t = transport.get_transport_from_url(url)
300
self.assertEqual(b'contents\n', t.get_bytes('a_file'))
300
self.assertEqual('contents\n', t.get_bytes('a_file'))
301
301
# However, if we just wait for more content from the server, it will
302
302
# eventually disconnect us.
303
303
# TODO: Use something like signal.alarm() so that if the server doesn't
308
308
# Now, we wait for timeout to trigger
309
309
err = process.stderr.readline()
310
310
self.assertEqual(
311
b'Connection Timeout: disconnecting client after 0.1 seconds\n',
311
'Connection Timeout: disconnecting client after 0.1 seconds\n',
313
313
self.assertServerFinishesCleanly(process)
315
315
def test_bzr_serve_graceful_shutdown(self):
316
big_contents = b'a' * 64 * 1024
316
big_contents = 'a'*64*1024
317
317
self.build_tree_contents([('bigfile', big_contents)])
318
318
process, url = self.start_server_port(['--client-timeout=1.0'])
319
319
t = transport.get_transport_from_url(url)
320
320
m = t.get_smart_medium()
321
321
c = client._SmartClient(m)
322
322
# Start, but don't finish a response
323
resp, response_handler = c.call_expecting_body(b'get', b'bigfile')
324
self.assertEqual((b'ok',), resp)
323
resp, response_handler = c.call_expecting_body('get', 'bigfile')
324
self.assertEqual(('ok',), resp)
325
325
# Note: process.send_signal is a Python 2.6ism
326
326
process.send_signal(signal.SIGHUP)
327
327
# Wait for the server to notice the signal, and then read the actual
328
328
# body of the response. That way we know that it is waiting for the
329
329
# request to finish
330
self.assertEqual(b'Requested to stop gracefully\n',
331
process.stderr.readline())
332
self.assertIn(process.stderr.readline(),
333
(b'', b'Waiting for 1 client(s) to finish\n'))
330
self.assertEqual('Requested to stop gracefully\n',
331
process.stderr.readline())
332
self.assertEqual('Waiting for 1 client(s) to finish\n',
333
process.stderr.readline())
334
334
body = response_handler.read_body_bytes()
335
335
if body != big_contents:
336
336
self.fail('Failed to properly read the contents of "bigfile"')
337
337
# Now that our request is finished, the medium should notice it has
338
338
# been disconnected.
339
self.assertEqual(b'', m.read_bytes(1))
339
self.assertEqual('', m.read_bytes(1))
340
340
# And the server should be stopping
341
341
self.assertEqual(0, process.wait())
344
344
class TestCmdServeChrooting(TestBzrServeBase):
346
346
def test_serve_tcp(self):
347
"""'brz serve' wraps the given --directory in a ChrootServer.
347
"""'bzr serve' wraps the given --directory in a ChrootServer.
349
349
So requests that search up through the parent directories (like
350
350
find_repositoryV3) will give "not found" responses, rather than
360
360
# The when_server_started method issued a find_repositoryV3 that should
361
361
# fail with 'norepository' because there are no repositories inside the
363
self.assertEqual((b'norepository',), self.client_resp)
363
self.assertEqual(('norepository',), self.client_resp)
365
365
def when_server_started(self):
366
366
# Connect to the TCP server and issue some requests and see what comes
373
373
resp = smart_client.call('BzrDirFormat.initialize', 'foo/')
375
375
resp = smart_client.call('BzrDir.find_repositoryV3', 'foo/')
376
except errors.ErrorFromSmartServer as e:
376
except errors.ErrorFromSmartServer, e:
377
377
resp = e.error_tuple
378
378
self.client_resp = resp
379
379
client_medium.disconnect()
400
400
bzr_server = BzrServerFactory(
401
401
self.fake_expanduser, lambda t: base_path)
402
402
mem_transport = self.get_transport()
403
mem_transport.mkdir('home')
404
mem_transport.mkdir('home/user')
403
mem_transport.mkdir_multi(['home', 'home/user'])
405
404
bzr_server.set_up(mem_transport, None, None, inet=True, timeout=4.0)
406
405
self.addCleanup(bzr_server.tear_down)
407
406
return bzr_server
413
412
def test_bzr_serve_does_not_expand_userdir_outside_base(self):
414
413
bzr_server = self.make_test_server('/foo')
416
bzr_server.smart_server.backing_transport.has('~user'))
414
self.assertFalse(bzr_server.smart_server.backing_transport.has('~user'))
418
416
def test_get_base_path(self):
419
417
"""cmd_serve will turn the --directory option into a LocalTransport
425
423
base_url = urlutils.local_path_to_url(base_dir) + '/'
426
424
# Define a fake 'protocol' to capture the transport that cmd_serve
427
425
# passes to serve_bzr.
429
426
def capture_transport(transport, host, port, inet, timeout):
430
427
self.bzr_serve_transport = transport
431
428
cmd = builtins.cmd_serve()
438
435
base_dir, server_maker.get_base_path(self.bzr_serve_transport))
440
437
cmd.run(directory=base_dir, protocol=capture_transport,
442
439
server_maker = BzrServerFactory()
443
440
self.assertEqual(base_url, self.bzr_serve_transport.base)
444
441
self.assertEqual(base_dir,
445
server_maker.get_base_path(self.bzr_serve_transport))
442
server_maker.get_base_path(self.bzr_serve_transport))
446
443
# Read-only, from a URL
447
444
cmd.run(directory=base_url, protocol=capture_transport)
448
445
server_maker = BzrServerFactory()