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