]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/test/test_runner.py
tests: bump up the timeout in this test that fails on FreeStorm's CentOS in order...
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / test / test_runner.py
1 from twisted.trial import unittest
2
3 from twisted.python import usage, runtime
4 from twisted.internet import threads
5
6 import os.path, re, sys, subprocess
7 from cStringIO import StringIO
8 from allmydata.util import fileutil, pollmixin
9 from allmydata.util.encodingutil import unicode_to_argv, unicode_to_output, get_filesystem_encoding
10 from allmydata.scripts import runner
11
12 from allmydata.test import common_util
13 import allmydata
14
15 timeout = 240
16
17 def get_root_from_file(src):
18     srcdir = os.path.dirname(os.path.dirname(os.path.normcase(os.path.realpath(src))))
19
20     root = os.path.dirname(srcdir)
21     if os.path.basename(srcdir) == 'site-packages':
22         if re.search(r'python.+\..+', os.path.basename(root)):
23             root = os.path.dirname(root)
24         root = os.path.dirname(root)
25     elif os.path.basename(root) == 'src':
26         root = os.path.dirname(root)
27
28     return root
29
30 srcfile = allmydata.__file__
31 rootdir = get_root_from_file(srcfile)
32
33 if hasattr(sys, 'frozen'):
34     bintahoe = os.path.join(rootdir, 'tahoe')
35     if sys.platform == "win32" and os.path.exists(bintahoe + '.exe'):
36         bintahoe += '.exe'
37 else:
38     bintahoe = os.path.join(rootdir, 'bin', 'tahoe')
39     if sys.platform == "win32":
40         bintahoe += '.pyscript'
41         if not os.path.exists(bintahoe):
42             alt_bintahoe = os.path.join(rootdir, 'Scripts', 'tahoe.pyscript')
43             if os.path.exists(alt_bintahoe):
44                 bintahoe = alt_bintahoe
45
46
47 class RunBinTahoeMixin:
48     def skip_if_cannot_run_bintahoe(self):
49         if not os.path.exists(bintahoe):
50             raise unittest.SkipTest("The bin/tahoe script isn't to be found in the expected location (%s), and I don't want to test a 'tahoe' executable that I find somewhere else, in case it isn't the right executable for this version of Tahoe. Perhaps running 'setup.py build' again will help." % (bintahoe,))
51
52     def skip_if_cannot_daemonize(self):
53         self.skip_if_cannot_run_bintahoe()
54         if runtime.platformType == "win32":
55             # twistd on windows doesn't daemonize. cygwin should work normally.
56             raise unittest.SkipTest("twistd does not fork under windows")
57
58     def run_bintahoe(self, args, stdin=None, python_options=[], env=None):
59         self.skip_if_cannot_run_bintahoe()
60
61         if hasattr(sys, 'frozen'):
62             if python_options:
63                 raise unittest.SkipTest("This test doesn't apply to frozen builds.")
64             command = [bintahoe] + args
65         else:
66             command = [sys.executable] + python_options + [bintahoe] + args
67
68         if stdin is None:
69             stdin_stream = None
70         else:
71             stdin_stream = subprocess.PIPE
72
73         def _run():
74             p = subprocess.Popen(command, stdin=stdin_stream, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
75             (out, err) = p.communicate(stdin)
76             return (out, err, p.returncode)
77         return threads.deferToThread(_run)
78
79
80 class BinTahoe(common_util.SignalMixin, unittest.TestCase, RunBinTahoeMixin):
81     def _check_right_code(self, file_to_check):
82         root_to_check = get_root_from_file(file_to_check)
83         if os.path.basename(root_to_check) == 'dist':
84             root_to_check = os.path.dirname(root_to_check)
85
86         cwd = os.path.normcase(os.path.realpath("."))
87         root_from_cwd = os.path.dirname(cwd)
88         if os.path.basename(root_from_cwd) == 'src':
89             root_from_cwd = os.path.dirname(root_from_cwd)
90
91         same = (root_from_cwd == root_to_check)
92         if not same:
93             try:
94                 same = os.path.samefile(root_from_cwd, root_to_check)
95             except AttributeError, e:
96                 e  # hush pyflakes
97
98         if not same:
99             msg = ("We seem to be testing the code at %r,\n"
100                    "(according to the source filename %r),\n"
101                    "but expected to be testing the code at %r.\n"
102                    % (root_to_check, file_to_check, root_from_cwd))
103
104             root_from_cwdu = os.path.dirname(os.path.normcase(os.path.normpath(os.getcwdu())))
105             if os.path.basename(root_from_cwdu) == u'src':
106                 root_from_cwdu = os.path.dirname(root_from_cwdu)
107
108             if not isinstance(root_from_cwd, unicode) and root_from_cwd.decode(get_filesystem_encoding(), 'replace') != root_from_cwdu:
109                 msg += ("However, this may be a false alarm because the current directory path\n"
110                         "is not representable in the filesystem encoding. Please run the tests\n"
111                         "from the root of the Tahoe-LAFS distribution at a non-Unicode path.")
112                 raise unittest.SkipTest(msg)
113             else:
114                 msg += "Please run the tests from the root of the Tahoe-LAFS distribution."
115                 self.fail(msg)
116
117     def test_the_right_code(self):
118         self._check_right_code(srcfile)
119
120     def test_import_in_repl(self):
121         d = self.run_bintahoe(["debug", "repl"],
122                               stdin="import allmydata; print; print allmydata.__file__")
123         def _cb(res):
124             out, err, rc_or_sig = res
125             self.failUnlessEqual(rc_or_sig, 0, str(res))
126             lines = out.splitlines()
127             self.failUnlessIn('>>>', lines[0], str(res))
128             self._check_right_code(lines[1])
129         d.addCallback(_cb)
130         return d
131     # The timeout was exceeded on FreeStorm's CentOS:
132     # http://tahoe-lafs.org/buildbot/builders/FreeStorm%20CentOS5-i386/builds/503/steps/test/logs/stdio
133     test_import_in_repl.timeout = 480
134
135     def test_path(self):
136         d = self.run_bintahoe(["--version-and-path"])
137         def _cb(res):
138             from allmydata import normalized_version
139
140             out, err, rc_or_sig = res
141             self.failUnlessEqual(rc_or_sig, 0, str(res))
142
143             # Fail unless the allmydata-tahoe package is *this* version *and*
144             # was loaded from *this* source directory.
145
146             required_verstr = str(allmydata.__version__)
147
148             self.failIfEqual(required_verstr, "unknown",
149                              "We don't know our version, because this distribution didn't come "
150                              "with a _version.py and 'setup.py darcsver' hasn't been run.")
151
152             srcdir = os.path.dirname(os.path.dirname(os.path.normcase(os.path.realpath(srcfile))))
153             info = (res, allmydata.__appname__, required_verstr, srcdir)
154
155             appverpath = out.split(')')[0]
156             (appver, path) = appverpath.split(' (')
157             (app, ver) = appver.split(': ')
158
159             self.failUnlessEqual(app, allmydata.__appname__, info)
160             self.failUnlessEqual(normalized_version(ver), normalized_version(required_verstr), info)
161             self.failUnlessEqual(path, srcdir, info)
162         d.addCallback(_cb)
163         return d
164
165     def test_unicode_arguments_and_output(self):
166         self.skip_if_cannot_run_bintahoe()
167
168         tricky = u"\u2621"
169         try:
170             tricky_arg = unicode_to_argv(tricky, mangle=True)
171             tricky_out = unicode_to_output(tricky)
172         except UnicodeEncodeError:
173             raise unittest.SkipTest("A non-ASCII argument/output could not be encoded on this platform.")
174
175         d = self.run_bintahoe([tricky_arg])
176         def _cb(res):
177             out, err, rc_or_sig = res
178             self.failUnlessEqual(rc_or_sig, 1, str(res))
179             self.failUnlessIn("Unknown command: "+tricky_out, out)
180         d.addCallback(_cb)
181         return d
182
183     def test_run_with_python_options(self):
184         # -t is a harmless option that warns about tabs.
185         d = self.run_bintahoe(["--version"], python_options=["-t"])
186         def _cb(res):
187             out, err, rc_or_sig = res
188             self.failUnlessEqual(rc_or_sig, 0, str(res))
189             self.failUnless(out.startswith(allmydata.__appname__+':'), str(res))
190         d.addCallback(_cb)
191         return d
192
193     def test_version_no_noise(self):
194         self.skip_if_cannot_run_bintahoe()
195
196         from allmydata import get_package_versions, normalized_version
197         twisted_ver = get_package_versions()['Twisted']
198
199         if not normalized_version(twisted_ver) >= normalized_version('9.0.0'):
200             raise unittest.SkipTest("We pass this test only with Twisted >= v9.0.0")
201
202         d = self.run_bintahoe(["--version"])
203         def _cb(res):
204             out, err, rc_or_sig = res
205             self.failUnlessEqual(rc_or_sig, 0, str(res))
206             self.failUnless(out.startswith(allmydata.__appname__+':'), str(res))
207             self.failIfIn("DeprecationWarning", out, str(res))
208             errlines = err.split("\n")
209             self.failIf([True for line in errlines if (line != "" and "UserWarning: Unbuilt egg for setuptools" not in line
210                                                                   and "from pkg_resources import load_entry_point" not in line)], str(res))
211             if err != "":
212                 raise unittest.SkipTest("This test is known not to pass on Ubuntu Lucid; see #1235.")
213         d.addCallback(_cb)
214         return d
215
216
217 class CreateNode(unittest.TestCase):
218     # exercise "tahoe create-node", create-introducer,
219     # create-key-generator, and create-stats-gatherer, by calling the
220     # corresponding code as a subroutine.
221
222     def workdir(self, name):
223         basedir = os.path.join("test_runner", "CreateNode", name)
224         fileutil.make_dirs(basedir)
225         return basedir
226
227     def run_tahoe(self, argv):
228         out,err = StringIO(), StringIO()
229         rc = runner.runner(argv, stdout=out, stderr=err)
230         return rc, out.getvalue(), err.getvalue()
231
232     def do_create(self, kind):
233         basedir = self.workdir("test_" + kind)
234         command = "create-" + kind
235         is_client = kind in ("node", "client")
236         tac = is_client and "tahoe-client.tac" or ("tahoe-" + kind + ".tac")
237
238         n1 = os.path.join(basedir, command + "-n1")
239         argv = ["--quiet", command, "--basedir", n1]
240         rc, out, err = self.run_tahoe(argv)
241         self.failUnlessEqual(err, "")
242         self.failUnlessEqual(out, "")
243         self.failUnlessEqual(rc, 0)
244         self.failUnless(os.path.exists(n1))
245         self.failUnless(os.path.exists(os.path.join(n1, tac)))
246
247         if is_client:
248             # tahoe.cfg should exist, and should have storage enabled for
249             # 'create-node', and disabled for 'create-client'.
250             tahoe_cfg = os.path.join(n1, "tahoe.cfg")
251             self.failUnless(os.path.exists(tahoe_cfg))
252             content = fileutil.read(tahoe_cfg).replace('\r\n', '\n')
253             if kind == "client":
254                 self.failUnless(re.search(r"\n\[storage\]\n#.*\nenabled = false\n", content), content)
255             else:
256                 self.failUnless(re.search(r"\n\[storage\]\n#.*\nenabled = true\n", content), content)
257                 self.failUnless("\nreserved_space = 1G\n" in content)
258
259             self.failUnless(re.search(r"\n\[drop_upload\]\n#.*\nenabled = false\n", content), content)
260
261         # creating the node a second time should be rejected
262         rc, out, err = self.run_tahoe(argv)
263         self.failIfEqual(rc, 0, str((out, err, rc)))
264         self.failUnlessEqual(out, "")
265         self.failUnless("is not empty." in err)
266
267         # Fail if there is a non-empty line that doesn't end with a
268         # punctuation mark.
269         for line in err.splitlines():
270             self.failIf(re.search("[\S][^\.!?]$", line), (line,))
271
272         # test that the non --basedir form works too
273         n2 = os.path.join(basedir, command + "-n2")
274         argv = ["--quiet", command, n2]
275         rc, out, err = self.run_tahoe(argv)
276         self.failUnlessEqual(err, "")
277         self.failUnlessEqual(out, "")
278         self.failUnlessEqual(rc, 0)
279         self.failUnless(os.path.exists(n2))
280         self.failUnless(os.path.exists(os.path.join(n2, tac)))
281
282         # test the --node-directory form
283         n3 = os.path.join(basedir, command + "-n3")
284         argv = ["--quiet", command, "--node-directory", n3]
285         rc, out, err = self.run_tahoe(argv)
286         self.failUnlessEqual(err, "")
287         self.failUnlessEqual(out, "")
288         self.failUnlessEqual(rc, 0)
289         self.failUnless(os.path.exists(n3))
290         self.failUnless(os.path.exists(os.path.join(n3, tac)))
291
292         # make sure it rejects too many arguments
293         argv = [command, "basedir", "extraarg"]
294         self.failUnlessRaises(usage.UsageError,
295                               runner.runner, argv,
296                               run_by_human=False)
297
298         # when creating a non-client, there is no default for the basedir
299         if not is_client:
300             argv = [command]
301             self.failUnlessRaises(usage.UsageError,
302                                   runner.runner, argv,
303                                   run_by_human=False)
304
305
306     def test_node(self):
307         self.do_create("node")
308
309     def test_client(self):
310         # create-client should behave like create-node --no-storage.
311         self.do_create("client")
312
313     def test_introducer(self):
314         self.do_create("introducer")
315
316     def test_key_generator(self):
317         self.do_create("key-generator")
318
319     def test_stats_gatherer(self):
320         self.do_create("stats-gatherer")
321
322     def test_subcommands(self):
323         # no arguments should trigger a command listing, via UsageError
324         self.failUnlessRaises(usage.UsageError,
325                               runner.runner,
326                               [],
327                               run_by_human=False)
328
329
330 class RunNode(common_util.SignalMixin, unittest.TestCase, pollmixin.PollMixin,
331               RunBinTahoeMixin):
332     # exercise "tahoe start", for both introducer, client node, and
333     # key-generator, by spawning "tahoe start" as a subprocess. This doesn't
334     # get us figleaf-based line-level coverage, but it does a better job of
335     # confirming that the user can actually run "./bin/tahoe start" and
336     # expect it to work. This verifies that bin/tahoe sets up PYTHONPATH and
337     # the like correctly.
338
339     # This doesn't work on cygwin (it hangs forever), so we skip this test
340     # when we're on cygwin. It is likely that "tahoe start" itself doesn't
341     # work on cygwin: twisted seems unable to provide a version of
342     # spawnProcess which really works there.
343
344     def workdir(self, name):
345         basedir = os.path.join("test_runner", "RunNode", name)
346         fileutil.make_dirs(basedir)
347         return basedir
348
349     def test_introducer(self):
350         self.skip_if_cannot_daemonize()
351         basedir = self.workdir("test_introducer")
352         c1 = os.path.join(basedir, "c1")
353         HOTLINE_FILE = os.path.join(c1, "suicide_prevention_hotline")
354         TWISTD_PID_FILE = os.path.join(c1, "twistd.pid")
355         INTRODUCER_FURL_FILE = os.path.join(c1, "introducer.furl")
356         PORTNUM_FILE = os.path.join(c1, "introducer.port")
357         NODE_URL_FILE = os.path.join(c1, "node.url")
358         CONFIG_FILE = os.path.join(c1, "tahoe.cfg")
359
360         d = self.run_bintahoe(["--quiet", "create-introducer", "--basedir", c1])
361         def _cb(res):
362             out, err, rc_or_sig = res
363             self.failUnlessEqual(rc_or_sig, 0)
364
365             # This makes sure that node.url is written, which allows us to
366             # detect when the introducer restarts in _node_has_restarted below.
367             config = fileutil.read(CONFIG_FILE)
368             self.failUnlessIn('\nweb.port = \n', config)
369             fileutil.write(CONFIG_FILE, config.replace('\nweb.port = \n', '\nweb.port = 0\n'))
370
371             # by writing this file, we get ten seconds before the node will
372             # exit. This insures that even if the test fails (and the 'stop'
373             # command doesn't work), the client should still terminate.
374             fileutil.write(HOTLINE_FILE, "")
375             # now it's safe to start the node
376         d.addCallback(_cb)
377
378         def _then_start_the_node(res):
379             return self.run_bintahoe(["--quiet", "start", c1])
380         d.addCallback(_then_start_the_node)
381
382         def _cb2(res):
383             out, err, rc_or_sig = res
384
385             fileutil.write(HOTLINE_FILE, "")
386             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
387             self.failUnlessEqual(rc_or_sig, 0, errstr)
388             self.failUnlessEqual(out, "", errstr)
389             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
390
391             # the parent (twistd) has exited. However, twistd writes the pid
392             # from the child, not the parent, so we can't expect twistd.pid
393             # to exist quite yet.
394
395             # the node is running, but it might not have made it past the
396             # first reactor turn yet, and if we kill it too early, it won't
397             # remove the twistd.pid file. So wait until it does something
398             # that we know it won't do until after the first turn.
399         d.addCallback(_cb2)
400
401         def _node_has_started():
402             return os.path.exists(INTRODUCER_FURL_FILE)
403         d.addCallback(lambda res: self.poll(_node_has_started))
404
405         def _started(res):
406             # read the introducer.furl and introducer.port files so we can check that their
407             # contents don't change on restart
408             self.furl = fileutil.read(INTRODUCER_FURL_FILE)
409             self.failUnless(os.path.exists(PORTNUM_FILE))
410             self.portnum = fileutil.read(PORTNUM_FILE)
411
412             fileutil.write(HOTLINE_FILE, "")
413             self.failUnless(os.path.exists(TWISTD_PID_FILE))
414             self.failUnless(os.path.exists(NODE_URL_FILE))
415
416             # rm this so we can detect when the second incarnation is ready
417             os.unlink(NODE_URL_FILE)
418             return self.run_bintahoe(["--quiet", "restart", c1])
419         d.addCallback(_started)
420
421         def _then(res):
422             out, err, rc_or_sig = res
423             fileutil.write(HOTLINE_FILE, "")
424             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
425             self.failUnlessEqual(rc_or_sig, 0, errstr)
426             self.failUnlessEqual(out, "", errstr)
427             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
428         d.addCallback(_then)
429
430         # again, the second incarnation of the node might not be ready yet,
431         # so poll until it is. This time INTRODUCER_FURL_FILE already
432         # exists, so we check for the existence of NODE_URL_FILE instead.
433         def _node_has_restarted():
434             return os.path.exists(NODE_URL_FILE) and os.path.exists(PORTNUM_FILE)
435         d.addCallback(lambda res: self.poll(_node_has_restarted))
436
437         def _check_same_furl_and_port(res):
438             self.failUnless(os.path.exists(INTRODUCER_FURL_FILE))
439             self.failUnlessEqual(self.furl, fileutil.read(INTRODUCER_FURL_FILE))
440             self.failUnlessEqual(self.portnum, fileutil.read(PORTNUM_FILE))
441         d.addCallback(_check_same_furl_and_port)
442
443         # now we can kill it. TODO: On a slow machine, the node might kill
444         # itself before we get a chance to, especially if spawning the
445         # 'tahoe stop' command takes a while.
446         def _stop(res):
447             fileutil.write(HOTLINE_FILE, "")
448             self.failUnless(os.path.exists(TWISTD_PID_FILE))
449
450             return self.run_bintahoe(["--quiet", "stop", c1])
451         d.addCallback(_stop)
452
453         def _after_stopping(res):
454             out, err, rc_or_sig = res
455             fileutil.write(HOTLINE_FILE, "")
456             # the parent has exited by now
457             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
458             self.failUnlessEqual(rc_or_sig, 0, errstr)
459             self.failUnlessEqual(out, "", errstr)
460             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
461             # the parent was supposed to poll and wait until it sees
462             # twistd.pid go away before it exits, so twistd.pid should be
463             # gone by now.
464             self.failIf(os.path.exists(TWISTD_PID_FILE))
465         d.addCallback(_after_stopping)
466         d.addBoth(self._remove, HOTLINE_FILE)
467         return d
468     test_introducer.timeout = 960
469
470     # This test hit the 120-second timeout on "Francois Lenny-armv5tel", then it hit a 240-second timeout on our feisty2.5 buildslave: http://allmydata.org/buildbot/builders/feisty2.5/builds/2381/steps/test/logs/test.log
471     # Then it hit the 480 second timeout on Francois's machine: http://tahoe-lafs.org/buildbot/builders/FranXois%20lenny-armv5tel/builds/449/steps/test/logs/stdio
472
473     def test_client_no_noise(self):
474         self.skip_if_cannot_daemonize()
475
476         from allmydata import get_package_versions, normalized_version
477         twisted_ver = get_package_versions()['Twisted']
478
479         if not normalized_version(twisted_ver) >= normalized_version('9.0.0'):
480             raise unittest.SkipTest("We pass this test only with Twisted >= v9.0.0")
481
482         basedir = self.workdir("test_client_no_noise")
483         c1 = os.path.join(basedir, "c1")
484         HOTLINE_FILE = os.path.join(c1, "suicide_prevention_hotline")
485         TWISTD_PID_FILE = os.path.join(c1, "twistd.pid")
486         PORTNUM_FILE = os.path.join(c1, "client.port")
487
488         d = self.run_bintahoe(["--quiet", "create-client", "--basedir", c1, "--webport", "0"])
489         def _cb(res):
490             out, err, rc_or_sig = res
491             errstr = "cc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
492             assert rc_or_sig == 0, errstr
493             self.failUnlessEqual(rc_or_sig, 0)
494
495             # By writing this file, we get two minutes before the client will exit. This ensures
496             # that even if the 'stop' command doesn't work (and the test fails), the client should
497             # still terminate.
498             fileutil.write(HOTLINE_FILE, "")
499             # now it's safe to start the node
500         d.addCallback(_cb)
501
502         def _start(res):
503             return self.run_bintahoe(["--quiet", "start", c1])
504         d.addCallback(_start)
505
506         def _cb2(res):
507             out, err, rc_or_sig = res
508             errstr = "cc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
509             fileutil.write(HOTLINE_FILE, "")
510             self.failUnlessEqual(rc_or_sig, 0, errstr)
511             self.failUnlessEqual(out, "", errstr) # If you emit noise, you fail this test.
512             errlines = err.split("\n")
513             self.failIf([True for line in errlines if (line != "" and "UserWarning: Unbuilt egg for setuptools" not in line
514                                                                   and "from pkg_resources import load_entry_point" not in line)], errstr)
515             if err != "":
516                 raise unittest.SkipTest("This test is known not to pass on Ubuntu Lucid; see #1235.")
517
518             # the parent (twistd) has exited. However, twistd writes the pid
519             # from the child, not the parent, so we can't expect twistd.pid
520             # to exist quite yet.
521
522             # the node is running, but it might not have made it past the
523             # first reactor turn yet, and if we kill it too early, it won't
524             # remove the twistd.pid file. So wait until it does something
525             # that we know it won't do until after the first turn.
526         d.addCallback(_cb2)
527
528         def _node_has_started():
529             return os.path.exists(PORTNUM_FILE)
530         d.addCallback(lambda res: self.poll(_node_has_started))
531
532         # now we can kill it. TODO: On a slow machine, the node might kill
533         # itself before we get a chance to, especially if spawning the
534         # 'tahoe stop' command takes a while.
535         def _stop(res):
536             self.failUnless(os.path.exists(TWISTD_PID_FILE), (TWISTD_PID_FILE, os.listdir(os.path.dirname(TWISTD_PID_FILE))))
537             return self.run_bintahoe(["--quiet", "stop", c1])
538         d.addCallback(_stop)
539         d.addBoth(self._remove, HOTLINE_FILE)
540         return d
541
542     def test_client(self):
543         self.skip_if_cannot_daemonize()
544         basedir = self.workdir("test_client")
545         c1 = os.path.join(basedir, "c1")
546         HOTLINE_FILE = os.path.join(c1, "suicide_prevention_hotline")
547         TWISTD_PID_FILE = os.path.join(c1, "twistd.pid")
548         PORTNUM_FILE = os.path.join(c1, "client.port")
549         NODE_URL_FILE = os.path.join(c1, "node.url")
550         CONFIG_FILE = os.path.join(c1, "tahoe.cfg")
551
552         d = self.run_bintahoe(["--quiet", "create-node", "--basedir", c1, "--webport", "0"])
553         def _cb(res):
554             out, err, rc_or_sig = res
555             self.failUnlessEqual(rc_or_sig, 0)
556
557             # Check that the --webport option worked.
558             config = fileutil.read(CONFIG_FILE)
559             self.failUnlessIn('\nweb.port = 0\n', config)
560
561             # By writing this file, we get two minutes before the client will exit. This ensures
562             # that even if the 'stop' command doesn't work (and the test fails), the client should
563             # still terminate.
564             fileutil.write(HOTLINE_FILE, "")
565             # now it's safe to start the node
566         d.addCallback(_cb)
567
568         def _start(res):
569             return self.run_bintahoe(["--quiet", "start", c1])
570         d.addCallback(_start)
571
572         def _cb2(res):
573             out, err, rc_or_sig = res
574             fileutil.write(HOTLINE_FILE, "")
575             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
576             self.failUnlessEqual(rc_or_sig, 0, errstr)
577             self.failUnlessEqual(out, "", errstr)
578             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
579
580             # the parent (twistd) has exited. However, twistd writes the pid
581             # from the child, not the parent, so we can't expect twistd.pid
582             # to exist quite yet.
583
584             # the node is running, but it might not have made it past the
585             # first reactor turn yet, and if we kill it too early, it won't
586             # remove the twistd.pid file. So wait until it does something
587             # that we know it won't do until after the first turn.
588         d.addCallback(_cb2)
589
590         def _node_has_started():
591             return os.path.exists(NODE_URL_FILE) and os.path.exists(PORTNUM_FILE)
592         d.addCallback(lambda res: self.poll(_node_has_started))
593
594         def _started(res):
595             # read the client.port file so we can check that its contents
596             # don't change on restart
597             self.portnum = fileutil.read(PORTNUM_FILE)
598
599             fileutil.write(HOTLINE_FILE, "")
600             self.failUnless(os.path.exists(TWISTD_PID_FILE))
601
602             # rm this so we can detect when the second incarnation is ready
603             os.unlink(NODE_URL_FILE)
604             return self.run_bintahoe(["--quiet", "restart", c1])
605         d.addCallback(_started)
606
607         def _cb3(res):
608             out, err, rc_or_sig = res
609
610             fileutil.write(HOTLINE_FILE, "")
611             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
612             self.failUnlessEqual(rc_or_sig, 0, errstr)
613             self.failUnlessEqual(out, "", errstr)
614             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
615         d.addCallback(_cb3)
616
617         # again, the second incarnation of the node might not be ready yet,
618         # so poll until it is
619         d.addCallback(lambda res: self.poll(_node_has_started))
620
621         def _check_same_port(res):
622             self.failUnlessEqual(self.portnum, fileutil.read(PORTNUM_FILE))
623         d.addCallback(_check_same_port)
624
625         # now we can kill it. TODO: On a slow machine, the node might kill
626         # itself before we get a chance to, especially if spawning the
627         # 'tahoe stop' command takes a while.
628         def _stop(res):
629             fileutil.write(HOTLINE_FILE, "")
630             self.failUnless(os.path.exists(TWISTD_PID_FILE), (TWISTD_PID_FILE, os.listdir(os.path.dirname(TWISTD_PID_FILE))))
631             return self.run_bintahoe(["--quiet", "stop", c1])
632         d.addCallback(_stop)
633
634         def _cb4(res):
635             out, err, rc_or_sig = res
636
637             fileutil.write(HOTLINE_FILE, "")
638             # the parent has exited by now
639             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
640             self.failUnlessEqual(rc_or_sig, 0, errstr)
641             self.failUnlessEqual(out, "", errstr)
642             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
643             # the parent was supposed to poll and wait until it sees
644             # twistd.pid go away before it exits, so twistd.pid should be
645             # gone by now.
646             self.failIf(os.path.exists(TWISTD_PID_FILE))
647         d.addCallback(_cb4)
648         d.addBoth(self._remove, HOTLINE_FILE)
649         return d
650
651     def _remove(self, res, file):
652         fileutil.remove(file)
653         return res
654
655     def test_baddir(self):
656         self.skip_if_cannot_daemonize()
657         basedir = self.workdir("test_baddir")
658         fileutil.make_dirs(basedir)
659
660         d = self.run_bintahoe(["--quiet", "start", "--basedir", basedir])
661         def _cb(res):
662             out, err, rc_or_sig = res
663             self.failUnlessEqual(rc_or_sig, 1)
664             self.failUnless("does not look like a node directory" in err, err)
665         d.addCallback(_cb)
666
667         def _then_stop_it(res):
668             return self.run_bintahoe(["--quiet", "stop", "--basedir", basedir])
669         d.addCallback(_then_stop_it)
670
671         def _cb2(res):
672             out, err, rc_or_sig = res
673             self.failUnlessEqual(rc_or_sig, 2)
674             self.failUnless("does not look like a running node directory" in err)
675         d.addCallback(_cb2)
676
677         def _then_start_in_bogus_basedir(res):
678             not_a_dir = os.path.join(basedir, "bogus")
679             return self.run_bintahoe(["--quiet", "start", "--basedir", not_a_dir])
680         d.addCallback(_then_start_in_bogus_basedir)
681
682         def _cb3(res):
683             out, err, rc_or_sig = res
684             self.failUnlessEqual(rc_or_sig, 1)
685             self.failUnless("does not look like a directory at all" in err, err)
686         d.addCallback(_cb3)
687         return d
688
689     def test_keygen(self):
690         self.skip_if_cannot_daemonize()
691         basedir = self.workdir("test_keygen")
692         c1 = os.path.join(basedir, "c1")
693         TWISTD_PID_FILE = os.path.join(c1, "twistd.pid")
694         KEYGEN_FURL_FILE = os.path.join(c1, "key_generator.furl")
695
696         d = self.run_bintahoe(["--quiet", "create-key-generator", "--basedir", c1])
697         def _cb(res):
698             out, err, rc_or_sig = res
699             self.failUnlessEqual(rc_or_sig, 0)
700         d.addCallback(_cb)
701
702         def _start(res):
703             return self.run_bintahoe(["--quiet", "start", c1])
704         d.addCallback(_start)
705
706         def _cb2(res):
707             out, err, rc_or_sig = res
708             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
709             self.failUnlessEqual(rc_or_sig, 0, errstr)
710             self.failUnlessEqual(out, "", errstr)
711             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
712
713             # the parent (twistd) has exited. However, twistd writes the pid
714             # from the child, not the parent, so we can't expect twistd.pid
715             # to exist quite yet.
716
717             # the node is running, but it might not have made it past the
718             # first reactor turn yet, and if we kill it too early, it won't
719             # remove the twistd.pid file. So wait until it does something
720             # that we know it won't do until after the first turn.
721         d.addCallback(_cb2)
722
723         def _node_has_started():
724             return os.path.exists(KEYGEN_FURL_FILE)
725         d.addCallback(lambda res: self.poll(_node_has_started))
726
727         def _started(res):
728             self.failUnless(os.path.exists(TWISTD_PID_FILE))
729             # rm this so we can detect when the second incarnation is ready
730             os.unlink(KEYGEN_FURL_FILE)
731             return self.run_bintahoe(["--quiet", "restart", c1])
732         d.addCallback(_started)
733
734         def _cb3(res):
735             out, err, rc_or_sig = res
736             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
737             self.failUnlessEqual(rc_or_sig, 0, errstr)
738             self.failUnlessEqual(out, "", errstr)
739             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
740         d.addCallback(_cb3)
741
742         # again, the second incarnation of the node might not be ready yet,
743         # so poll until it is
744         d.addCallback(lambda res: self.poll(_node_has_started))
745
746         # now we can kill it. TODO: On a slow machine, the node might kill
747         # itself before we get a chance too, especially if spawning the
748         # 'tahoe stop' command takes a while.
749         def _stop(res):
750             self.failUnless(os.path.exists(TWISTD_PID_FILE))
751             return self.run_bintahoe(["--quiet", "stop", c1])
752         d.addCallback(_stop)
753
754         def _cb4(res):
755             out, err, rc_or_sig = res
756             # the parent has exited by now
757             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
758             self.failUnlessEqual(rc_or_sig, 0, errstr)
759             self.failUnlessEqual(out, "", errstr)
760             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
761             # the parent was supposed to poll and wait until it sees
762             # twistd.pid go away before it exits, so twistd.pid should be
763             # gone by now.
764             self.failIf(os.path.exists(TWISTD_PID_FILE))
765         d.addCallback(_cb4)
766         return d