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