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