]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/test/test_runner.py
Show git branch in version output. fixes #1953
[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         # This is needed if we are running in a temporary directory created by 'make tmpfstest'.
92         if os.path.basename(root_from_cwd).startswith('tmp'):
93             root_from_cwd = os.path.dirname(root_from_cwd)
94
95         same = (root_from_cwd == root_to_check)
96         if not same:
97             try:
98                 same = os.path.samefile(root_from_cwd, root_to_check)
99             except AttributeError, e:
100                 e  # hush pyflakes
101
102         if not same:
103             msg = ("We seem to be testing the code at %r,\n"
104                    "(according to the source filename %r),\n"
105                    "but expected to be testing the code at %r.\n"
106                    % (root_to_check, file_to_check, root_from_cwd))
107
108             root_from_cwdu = os.path.dirname(os.path.normcase(os.path.normpath(os.getcwdu())))
109             if os.path.basename(root_from_cwdu) == u'src':
110                 root_from_cwdu = os.path.dirname(root_from_cwdu)
111
112             # This is needed if we are running in a temporary directory created by 'make tmpfstest'.
113             if os.path.basename(root_from_cwdu).startswith(u'tmp'):
114                 root_from_cwdu = os.path.dirname(root_from_cwdu)
115
116             if not isinstance(root_from_cwd, unicode) and root_from_cwd.decode(get_filesystem_encoding(), 'replace') != root_from_cwdu:
117                 msg += ("However, this may be a false alarm because the current directory path\n"
118                         "is not representable in the filesystem encoding. Please run the tests\n"
119                         "from the root of the Tahoe-LAFS distribution at a non-Unicode path.")
120                 raise unittest.SkipTest(msg)
121             else:
122                 msg += "Please run the tests from the root of the Tahoe-LAFS distribution."
123                 self.fail(msg)
124
125     def test_the_right_code(self):
126         self._check_right_code(srcfile)
127
128     def test_import_in_repl(self):
129         d = self.run_bintahoe(["debug", "repl"],
130                               stdin="import allmydata; print; print allmydata.__file__")
131         def _cb(res):
132             out, err, rc_or_sig = res
133             self.failUnlessEqual(rc_or_sig, 0, str(res))
134             lines = out.splitlines()
135             self.failUnlessIn('>>>', lines[0], str(res))
136             self._check_right_code(lines[1])
137         d.addCallback(_cb)
138         return d
139     # The timeout was exceeded on FreeStorm's CentOS5-i386.
140     test_import_in_repl.timeout = 480
141
142     def test_path(self):
143         d = self.run_bintahoe(["--version-and-path"])
144         def _cb(res):
145             from allmydata import normalized_version
146
147             out, err, rc_or_sig = res
148             self.failUnlessEqual(rc_or_sig, 0, str(res))
149
150             # Fail unless the allmydata-tahoe package is *this* version *and*
151             # was loaded from *this* source directory.
152
153             required_verstr = str(allmydata.__version__)
154
155             self.failIfEqual(required_verstr, "unknown",
156                              "We don't know our version, because this distribution didn't come "
157                              "with a _version.py and 'setup.py update_version' hasn't been run.")
158
159             srcdir = os.path.dirname(os.path.dirname(os.path.normcase(os.path.realpath(srcfile))))
160             info = repr((res, allmydata.__appname__, required_verstr, srcdir))
161
162             appverpath = out.split(')')[0]
163             (appverfull, path) = appverpath.split('] (')
164             (appver, comment) = appverfull.split(' [')
165             (branch, full_version) = comment.split(': ')
166             (app, ver) = appver.split(': ')
167
168             self.failUnlessEqual(app, allmydata.__appname__, info)
169             norm_ver = normalized_version(ver)
170             norm_required = normalized_version(required_verstr)
171             self.failUnlessEqual(norm_ver, norm_required, info)
172             self.failUnlessEqual(path, srcdir, info)
173             self.failUnlessEqual(branch, allmydata.branch)
174             self.failUnlessEqual(full_version, allmydata.full_version)
175         d.addCallback(_cb)
176         return d
177
178     def test_unicode_arguments_and_output(self):
179         self.skip_if_cannot_run_bintahoe()
180
181         tricky = u"\u2621"
182         try:
183             tricky_arg = unicode_to_argv(tricky, mangle=True)
184             tricky_out = unicode_to_output(tricky)
185         except UnicodeEncodeError:
186             raise unittest.SkipTest("A non-ASCII argument/output could not be encoded on this platform.")
187
188         d = self.run_bintahoe([tricky_arg])
189         def _cb(res):
190             out, err, rc_or_sig = res
191             self.failUnlessEqual(rc_or_sig, 1, str(res))
192             self.failUnlessIn("Unknown command: "+tricky_out, out)
193         d.addCallback(_cb)
194         return d
195
196     def test_run_with_python_options(self):
197         # -t is a harmless option that warns about tabs.
198         d = self.run_bintahoe(["--version"], python_options=["-t"])
199         def _cb(res):
200             out, err, rc_or_sig = res
201             self.failUnlessEqual(rc_or_sig, 0, str(res))
202             self.failUnless(out.startswith(allmydata.__appname__+':'), str(res))
203         d.addCallback(_cb)
204         return d
205
206     def test_version_no_noise(self):
207         self.skip_if_cannot_run_bintahoe()
208
209         d = self.run_bintahoe(["--version"])
210         def _cb(res):
211             out, err, rc_or_sig = res
212             self.failUnlessEqual(rc_or_sig, 0, str(res))
213             self.failUnless(out.startswith(allmydata.__appname__+':'), str(res))
214             self.failIfIn("DeprecationWarning", out, str(res))
215             errlines = err.split("\n")
216             self.failIf([True for line in errlines if (line != "" and "UserWarning: Unbuilt egg for setuptools" not in line
217                                                                   and "from pkg_resources import load_entry_point" not in line)], str(res))
218             if err != "":
219                 raise unittest.SkipTest("This test is known not to pass on Ubuntu Lucid; see #1235.")
220         d.addCallback(_cb)
221         return d
222
223
224 class CreateNode(unittest.TestCase):
225     # exercise "tahoe create-node", create-introducer,
226     # create-key-generator, and create-stats-gatherer, by calling the
227     # corresponding code as a subroutine.
228
229     def workdir(self, name):
230         basedir = os.path.join("test_runner", "CreateNode", name)
231         fileutil.make_dirs(basedir)
232         return basedir
233
234     def run_tahoe(self, argv):
235         out,err = StringIO(), StringIO()
236         rc = runner.runner(argv, stdout=out, stderr=err)
237         return rc, out.getvalue(), err.getvalue()
238
239     def do_create(self, kind):
240         basedir = self.workdir("test_" + kind)
241         command = "create-" + kind
242         is_client = kind in ("node", "client")
243         tac = is_client and "tahoe-client.tac" or ("tahoe-" + kind + ".tac")
244
245         n1 = os.path.join(basedir, command + "-n1")
246         argv = ["--quiet", command, "--basedir", n1]
247         rc, out, err = self.run_tahoe(argv)
248         self.failUnlessEqual(err, "")
249         self.failUnlessEqual(out, "")
250         self.failUnlessEqual(rc, 0)
251         self.failUnless(os.path.exists(n1))
252         self.failUnless(os.path.exists(os.path.join(n1, tac)))
253
254         if is_client:
255             # tahoe.cfg should exist, and should have storage enabled for
256             # 'create-node', and disabled for 'create-client'.
257             tahoe_cfg = os.path.join(n1, "tahoe.cfg")
258             self.failUnless(os.path.exists(tahoe_cfg))
259             content = fileutil.read(tahoe_cfg).replace('\r\n', '\n')
260             if kind == "client":
261                 self.failUnless(re.search(r"\n\[storage\]\n#.*\nenabled = false\n", content), content)
262             else:
263                 self.failUnless(re.search(r"\n\[storage\]\n#.*\nenabled = true\n", content), content)
264                 self.failUnless("\nreserved_space = 1G\n" in content)
265
266             self.failUnless(re.search(r"\n\[drop_upload\]\n#.*\nenabled = false\n", content), content)
267
268         # creating the node a second time should be rejected
269         rc, out, err = self.run_tahoe(argv)
270         self.failIfEqual(rc, 0, str((out, err, rc)))
271         self.failUnlessEqual(out, "")
272         self.failUnless("is not empty." in err)
273
274         # Fail if there is a non-empty line that doesn't end with a
275         # punctuation mark.
276         for line in err.splitlines():
277             self.failIf(re.search("[\S][^\.!?]$", line), (line,))
278
279         # test that the non --basedir form works too
280         n2 = os.path.join(basedir, command + "-n2")
281         argv = ["--quiet", command, n2]
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(n2))
287         self.failUnless(os.path.exists(os.path.join(n2, tac)))
288
289         # test the --node-directory form
290         n3 = os.path.join(basedir, command + "-n3")
291         argv = ["--quiet", "--node-directory", n3, command]
292         rc, out, err = self.run_tahoe(argv)
293         self.failUnlessEqual(err, "")
294         self.failUnlessEqual(out, "")
295         self.failUnlessEqual(rc, 0)
296         self.failUnless(os.path.exists(n3))
297         self.failUnless(os.path.exists(os.path.join(n3, tac)))
298
299         # make sure it rejects too many arguments
300         argv = [command, "basedir", "extraarg"]
301         self.failUnlessRaises(usage.UsageError,
302                               runner.runner, argv,
303                               run_by_human=False)
304
305         # when creating a non-client, there is no default for the basedir
306         if not is_client:
307             argv = [command]
308             self.failUnlessRaises(usage.UsageError,
309                                   runner.runner, argv,
310                                   run_by_human=False)
311
312
313     def test_node(self):
314         self.do_create("node")
315
316     def test_client(self):
317         # create-client should behave like create-node --no-storage.
318         self.do_create("client")
319
320     def test_introducer(self):
321         self.do_create("introducer")
322
323     def test_key_generator(self):
324         self.do_create("key-generator")
325
326     def test_stats_gatherer(self):
327         self.do_create("stats-gatherer")
328
329     def test_subcommands(self):
330         # no arguments should trigger a command listing, via UsageError
331         self.failUnlessRaises(usage.UsageError,
332                               runner.runner,
333                               [],
334                               run_by_human=False)
335
336
337 class RunNode(common_util.SignalMixin, unittest.TestCase, pollmixin.PollMixin,
338               RunBinTahoeMixin):
339     # exercise "tahoe start", for both introducer, client node, and
340     # key-generator, by spawning "tahoe start" as a subprocess. This doesn't
341     # get us figleaf-based line-level coverage, but it does a better job of
342     # confirming that the user can actually run "./bin/tahoe start" and
343     # expect it to work. This verifies that bin/tahoe sets up PYTHONPATH and
344     # the like correctly.
345
346     # This doesn't work on cygwin (it hangs forever), so we skip this test
347     # when we're on cygwin. It is likely that "tahoe start" itself doesn't
348     # work on cygwin: twisted seems unable to provide a version of
349     # spawnProcess which really works there.
350
351     def workdir(self, name):
352         basedir = os.path.join("test_runner", "RunNode", name)
353         fileutil.make_dirs(basedir)
354         return basedir
355
356     def test_introducer(self):
357         self.skip_if_cannot_daemonize()
358         basedir = self.workdir("test_introducer")
359         c1 = os.path.join(basedir, "c1")
360         HOTLINE_FILE = os.path.join(c1, "suicide_prevention_hotline")
361         TWISTD_PID_FILE = os.path.join(c1, "twistd.pid")
362         INTRODUCER_FURL_FILE = os.path.join(c1, "private", "introducer.furl")
363         PORTNUM_FILE = os.path.join(c1, "introducer.port")
364         NODE_URL_FILE = os.path.join(c1, "node.url")
365         CONFIG_FILE = os.path.join(c1, "tahoe.cfg")
366
367         d = self.run_bintahoe(["--quiet", "create-introducer", "--basedir", c1])
368         def _cb(res):
369             out, err, rc_or_sig = res
370             self.failUnlessEqual(rc_or_sig, 0)
371
372             # This makes sure that node.url is written, which allows us to
373             # detect when the introducer restarts in _node_has_restarted below.
374             config = fileutil.read(CONFIG_FILE)
375             self.failUnlessIn('\nweb.port = \n', config)
376             fileutil.write(CONFIG_FILE, config.replace('\nweb.port = \n', '\nweb.port = 0\n'))
377
378             # by writing this file, we get ten seconds before the node will
379             # exit. This insures that even if the test fails (and the 'stop'
380             # command doesn't work), the client should still terminate.
381             fileutil.write(HOTLINE_FILE, "")
382             # now it's safe to start the node
383         d.addCallback(_cb)
384
385         def _then_start_the_node(res):
386             return self.run_bintahoe(["--quiet", "start", c1])
387         d.addCallback(_then_start_the_node)
388
389         def _cb2(res):
390             out, err, rc_or_sig = res
391
392             fileutil.write(HOTLINE_FILE, "")
393             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
394             self.failUnlessEqual(rc_or_sig, 0, errstr)
395             self.failUnlessEqual(out, "", errstr)
396             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
397
398             # the parent (twistd) has exited. However, twistd writes the pid
399             # from the child, not the parent, so we can't expect twistd.pid
400             # to exist quite yet.
401
402             # the node is running, but it might not have made it past the
403             # first reactor turn yet, and if we kill it too early, it won't
404             # remove the twistd.pid file. So wait until it does something
405             # that we know it won't do until after the first turn.
406         d.addCallback(_cb2)
407
408         def _node_has_started():
409             return os.path.exists(INTRODUCER_FURL_FILE)
410         d.addCallback(lambda res: self.poll(_node_has_started))
411
412         def _started(res):
413             # read the introducer.furl and introducer.port files so we can
414             # check that their contents don't change on restart
415             self.furl = fileutil.read(INTRODUCER_FURL_FILE)
416             self.failUnless(os.path.exists(PORTNUM_FILE))
417             self.portnum = fileutil.read(PORTNUM_FILE)
418
419             fileutil.write(HOTLINE_FILE, "")
420             self.failUnless(os.path.exists(TWISTD_PID_FILE))
421             self.failUnless(os.path.exists(NODE_URL_FILE))
422
423             # rm this so we can detect when the second incarnation is ready
424             os.unlink(NODE_URL_FILE)
425             return self.run_bintahoe(["--quiet", "restart", c1])
426         d.addCallback(_started)
427
428         def _then(res):
429             out, err, rc_or_sig = res
430             fileutil.write(HOTLINE_FILE, "")
431             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
432             self.failUnlessEqual(rc_or_sig, 0, errstr)
433             self.failUnlessEqual(out, "", errstr)
434             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
435         d.addCallback(_then)
436
437         # again, the second incarnation of the node might not be ready yet,
438         # so poll until it is. This time INTRODUCER_FURL_FILE already
439         # exists, so we check for the existence of NODE_URL_FILE instead.
440         def _node_has_restarted():
441             return os.path.exists(NODE_URL_FILE) and os.path.exists(PORTNUM_FILE)
442         d.addCallback(lambda res: self.poll(_node_has_restarted))
443
444         def _check_same_furl_and_port(res):
445             self.failUnless(os.path.exists(INTRODUCER_FURL_FILE))
446             self.failUnlessEqual(self.furl, fileutil.read(INTRODUCER_FURL_FILE))
447             self.failUnlessEqual(self.portnum, fileutil.read(PORTNUM_FILE))
448         d.addCallback(_check_same_furl_and_port)
449
450         # now we can kill it. TODO: On a slow machine, the node might kill
451         # itself before we get a chance to, especially if spawning the
452         # 'tahoe stop' command takes a while.
453         def _stop(res):
454             fileutil.write(HOTLINE_FILE, "")
455             self.failUnless(os.path.exists(TWISTD_PID_FILE))
456
457             return self.run_bintahoe(["--quiet", "stop", c1])
458         d.addCallback(_stop)
459
460         def _after_stopping(res):
461             out, err, rc_or_sig = res
462             fileutil.write(HOTLINE_FILE, "")
463             # the parent has exited by now
464             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
465             self.failUnlessEqual(rc_or_sig, 0, errstr)
466             self.failUnlessEqual(out, "", errstr)
467             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
468             # the parent was supposed to poll and wait until it sees
469             # twistd.pid go away before it exits, so twistd.pid should be
470             # gone by now.
471             self.failIf(os.path.exists(TWISTD_PID_FILE))
472         d.addCallback(_after_stopping)
473         d.addBoth(self._remove, HOTLINE_FILE)
474         return d
475     # This test has hit a 240-second timeout on our feisty2.5 buildslave, and a 480-second timeout
476     # on Francois's Lenny-armv5tel buildslave.
477     test_introducer.timeout = 960
478
479     def test_client_no_noise(self):
480         self.skip_if_cannot_daemonize()
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             # this depends upon both files being created atomically
592             return os.path.exists(NODE_URL_FILE) and os.path.exists(PORTNUM_FILE)
593         d.addCallback(lambda res: self.poll(_node_has_started))
594
595         def _started(res):
596             # read the client.port file so we can check that its contents
597             # don't change on restart
598             self.portnum = fileutil.read(PORTNUM_FILE)
599
600             fileutil.write(HOTLINE_FILE, "")
601             self.failUnless(os.path.exists(TWISTD_PID_FILE))
602
603             # rm this so we can detect when the second incarnation is ready
604             os.unlink(NODE_URL_FILE)
605             return self.run_bintahoe(["--quiet", "restart", c1])
606         d.addCallback(_started)
607
608         def _cb3(res):
609             out, err, rc_or_sig = res
610
611             fileutil.write(HOTLINE_FILE, "")
612             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
613             self.failUnlessEqual(rc_or_sig, 0, errstr)
614             self.failUnlessEqual(out, "", errstr)
615             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
616         d.addCallback(_cb3)
617
618         # again, the second incarnation of the node might not be ready yet,
619         # so poll until it is
620         d.addCallback(lambda res: self.poll(_node_has_started))
621
622         def _check_same_port(res):
623             self.failUnlessEqual(self.portnum, fileutil.read(PORTNUM_FILE))
624         d.addCallback(_check_same_port)
625
626         # now we can kill it. TODO: On a slow machine, the node might kill
627         # itself before we get a chance to, especially if spawning the
628         # 'tahoe stop' command takes a while.
629         def _stop(res):
630             fileutil.write(HOTLINE_FILE, "")
631             self.failUnless(os.path.exists(TWISTD_PID_FILE),
632                             (TWISTD_PID_FILE,
633                              os.listdir(os.path.dirname(TWISTD_PID_FILE))))
634             return self.run_bintahoe(["--quiet", "stop", c1])
635         d.addCallback(_stop)
636
637         def _cb4(res):
638             out, err, rc_or_sig = res
639
640             fileutil.write(HOTLINE_FILE, "")
641             # the parent has exited by now
642             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
643             self.failUnlessEqual(rc_or_sig, 0, errstr)
644             self.failUnlessEqual(out, "", errstr)
645             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
646             # the parent was supposed to poll and wait until it sees
647             # twistd.pid go away before it exits, so twistd.pid should be
648             # gone by now.
649             self.failIf(os.path.exists(TWISTD_PID_FILE))
650         d.addCallback(_cb4)
651         d.addBoth(self._remove, HOTLINE_FILE)
652         return d
653
654     def _remove(self, res, file):
655         fileutil.remove(file)
656         return res
657
658     def test_baddir(self):
659         self.skip_if_cannot_daemonize()
660         basedir = self.workdir("test_baddir")
661         fileutil.make_dirs(basedir)
662
663         d = self.run_bintahoe(["--quiet", "start", "--basedir", basedir])
664         def _cb(res):
665             out, err, rc_or_sig = res
666             self.failUnlessEqual(rc_or_sig, 1)
667             self.failUnless("does not look like a node directory" in err, err)
668         d.addCallback(_cb)
669
670         def _then_stop_it(res):
671             return self.run_bintahoe(["--quiet", "stop", "--basedir", basedir])
672         d.addCallback(_then_stop_it)
673
674         def _cb2(res):
675             out, err, rc_or_sig = res
676             self.failUnlessEqual(rc_or_sig, 2)
677             self.failUnless("does not look like a running node directory" in err)
678         d.addCallback(_cb2)
679
680         def _then_start_in_bogus_basedir(res):
681             not_a_dir = os.path.join(basedir, "bogus")
682             return self.run_bintahoe(["--quiet", "start", "--basedir", not_a_dir])
683         d.addCallback(_then_start_in_bogus_basedir)
684
685         def _cb3(res):
686             out, err, rc_or_sig = res
687             self.failUnlessEqual(rc_or_sig, 1)
688             self.failUnless("does not look like a directory at all" in err, err)
689         d.addCallback(_cb3)
690         return d
691
692     def test_keygen(self):
693         self.skip_if_cannot_daemonize()
694         basedir = self.workdir("test_keygen")
695         c1 = os.path.join(basedir, "c1")
696         TWISTD_PID_FILE = os.path.join(c1, "twistd.pid")
697         KEYGEN_FURL_FILE = os.path.join(c1, "key_generator.furl")
698
699         d = self.run_bintahoe(["--quiet", "create-key-generator", "--basedir", c1])
700         def _cb(res):
701             out, err, rc_or_sig = res
702             self.failUnlessEqual(rc_or_sig, 0)
703         d.addCallback(_cb)
704
705         def _start(res):
706             return self.run_bintahoe(["--quiet", "start", c1])
707         d.addCallback(_start)
708
709         def _cb2(res):
710             out, err, rc_or_sig = res
711             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
712             self.failUnlessEqual(rc_or_sig, 0, errstr)
713             self.failUnlessEqual(out, "", errstr)
714             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
715
716             # the parent (twistd) has exited. However, twistd writes the pid
717             # from the child, not the parent, so we can't expect twistd.pid
718             # to exist quite yet.
719
720             # the node is running, but it might not have made it past the
721             # first reactor turn yet, and if we kill it too early, it won't
722             # remove the twistd.pid file. So wait until it does something
723             # that we know it won't do until after the first turn.
724         d.addCallback(_cb2)
725
726         def _node_has_started():
727             return os.path.exists(KEYGEN_FURL_FILE)
728         d.addCallback(lambda res: self.poll(_node_has_started))
729
730         def _started(res):
731             self.failUnless(os.path.exists(TWISTD_PID_FILE))
732             # rm this so we can detect when the second incarnation is ready
733             os.unlink(KEYGEN_FURL_FILE)
734             return self.run_bintahoe(["--quiet", "restart", c1])
735         d.addCallback(_started)
736
737         def _cb3(res):
738             out, err, rc_or_sig = res
739             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
740             self.failUnlessEqual(rc_or_sig, 0, errstr)
741             self.failUnlessEqual(out, "", errstr)
742             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
743         d.addCallback(_cb3)
744
745         # again, the second incarnation of the node might not be ready yet,
746         # so poll until it is
747         d.addCallback(lambda res: self.poll(_node_has_started))
748
749         # now we can kill it. TODO: On a slow machine, the node might kill
750         # itself before we get a chance too, especially if spawning the
751         # 'tahoe stop' command takes a while.
752         def _stop(res):
753             self.failUnless(os.path.exists(TWISTD_PID_FILE))
754             return self.run_bintahoe(["--quiet", "stop", c1])
755         d.addCallback(_stop)
756
757         def _cb4(res):
758             out, err, rc_or_sig = res
759             # the parent has exited by now
760             errstr = "rc=%d, OUT: '%s', ERR: '%s'" % (rc_or_sig, out, err)
761             self.failUnlessEqual(rc_or_sig, 0, errstr)
762             self.failUnlessEqual(out, "", errstr)
763             # self.failUnlessEqual(err, "", errstr) # See test_client_no_noise -- for now we ignore noise.
764             # the parent was supposed to poll and wait until it sees
765             # twistd.pid go away before it exits, so twistd.pid should be
766             # gone by now.
767             self.failIf(os.path.exists(TWISTD_PID_FILE))
768         d.addCallback(_cb4)
769         return d