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