Debian Codegraph @

tests/CLIClushTest.py

raw symbols SCIP
1 # ClusterShell.CLI.Clush test suite
2 # Written by S. Thiell
3
4 """Unit test for CLI.Clush"""
5
6 import codecs
7 import errno
8 import os
9 from os.path import basename, dirname
10 import pwd
11 import re
12 import resource
13 import signal
14 import sys
15 import tempfile
16 from textwrap import dedent
17 import threading
18 import time
19 import unittest
20
21 from subprocess import Popen, PIPE
22
23 from .TLib import *
24 import ClusterShell.CLI.Clush
25 from ClusterShell.CLI.Clush import main
26 from ClusterShell.Defaults import DEFAULTS
27 from ClusterShell.NodeSet import NodeSet
28 from ClusterShell.NodeSet import set_std_group_resolver, \
29 set_std_group_resolver_config
30 from ClusterShell.Task import task_cleanup
31
32 from ClusterShell.Worker.EngineClient import EngineClientNotSupportedError
33
34
35 class CLIClushTest_A(unittest.TestCase):
36 """Unit test class for testing CLI/Clush.py"""
37
38 def setUp(self):
39 """define constants used in tests"""
40 s = "%s: ok\n" % HOSTNAME
41 self.output_ok = s.encode()
42
43 s = "\x1b[94m%s: \x1b[0mok\n" % HOSTNAME
44 self.output_ok_color = s.encode()
45
46 self.soft, self.hard = resource.getrlimit(resource.RLIMIT_NOFILE)
47
48 def tearDown(self):
49 """cleanup all tasks"""
50 task_cleanup()
51
52 # we played with fd_max: restore original nofile resource limits
53 resource.setrlimit(resource.RLIMIT_NOFILE, (self.soft, self.hard))
54
55 def _clush_t(self, args, stdin, expected_stdout, expected_rc=0,
56 expected_stderr=None):
57 """This new version allows code coverage checking by calling clush's
58 main entry point."""
59 def raw_input_mock(prompt):
60 # trusty sleep
61 wait_time = 60
62 start = time.time()
63 while time.time() - start < wait_time:
64 time.sleep(wait_time - (time.time() - start))
65 return ""
66 try:
67 raw_input_save = ClusterShell.CLI.Clush.raw_input
68 except:
69 raw_input_save = raw_input
70 ClusterShell.CLI.Clush.raw_input = raw_input_mock
71 try:
72 CLI_main(self, main, ['clush'] + args, stdin, expected_stdout,
73 expected_rc, expected_stderr)
74 finally:
75 ClusterShell.CLI.Clush.raw_input = raw_input_save
76
77 def test_000_display(self):
78 """test clush (display options)"""
79 self._clush_t(["-w", HOSTNAME, "true"], None, b"")
80
81 s = "%s: ok ok\n" % HOSTNAME
82 exp_output2 = s.encode()
83
84 self._clush_t(["-w", HOSTNAME, "echo", "ok"], None, self.output_ok)
85 self._clush_t(["-w", HOSTNAME, "echo", "ok", "ok"], None, exp_output2)
86 self._clush_t(["-N", "-w", HOSTNAME, "echo", "ok", "ok"], None,
87 b"ok ok\n")
88 self._clush_t(["-w", "badhost,%s" % HOSTNAME, "-x", "badhost", "echo",
89 "ok"], None, self.output_ok)
90 self._clush_t(["-qw", HOSTNAME, "echo", "ok"], None, self.output_ok)
91 self._clush_t(["-vw", HOSTNAME, "echo", "ok"], None, self.output_ok)
92 self._clush_t(["-qvw", HOSTNAME, "echo", "ok"], None, self.output_ok)
93 self._clush_t(["-Sw", HOSTNAME, "echo", "ok"], None, self.output_ok)
94 self._clush_t(["-Sqw", HOSTNAME, "echo", "ok"], None, self.output_ok)
95 self._clush_t(["-Svw", HOSTNAME, "echo", "ok"], None, self.output_ok)
96 self._clush_t(["--nostdin", "-w", HOSTNAME, "echo", "ok"], None,
97 self.output_ok)
98
99 self._clush_t(["-w", HOSTNAME, "--color=always", "echo", "ok"], None,
100 self.output_ok_color)
101 self._clush_t(["-w", HOSTNAME, "--color=never", "echo", "ok"], None,
102 self.output_ok)
103
104 # issue #352
105 self._clush_t(["-N", "-R", "exec", "-w", 'foo[1-2]', "-b",
106 "echo", "test"], None, b"test\n")
107
108 def test_001_display_tty(self):
109 """test clush (display options) [tty]"""
110 setattr(ClusterShell.CLI.Clush, '_f_user_interaction', True)
111 try:
112 self.test_000_display()
113 finally:
114 delattr(ClusterShell.CLI.Clush, '_f_user_interaction')
115
116 def test_002_fanout(self):
117 """test clush (fanout)"""
118 self._clush_t(["-f", "10", "-w", HOSTNAME, "true"], None, b"")
119 self._clush_t(["-f", "1", "-w", HOSTNAME, "true"], None, b"")
120 self._clush_t(["-f", "1", "-w", HOSTNAME, "echo", "ok"], None,
121 self.output_ok)
122
123 def test_003_fanout_tty(self):
124 """test clush (fanout) [tty]"""
125 setattr(ClusterShell.CLI.Clush, '_f_user_interaction', True)
126 try:
127 self.test_002_fanout()
128 finally:
129 delattr(ClusterShell.CLI.Clush, '_f_user_interaction')
130
131 def test_004_ssh_options(self):
132 """test clush (ssh options)"""
133 self._clush_t(["-o", "-oStrictHostKeyChecking=no", "-w", HOSTNAME,
134 "echo", "ok"], None, self.output_ok)
135 self._clush_t(["-o", "-oStrictHostKeyChecking=no -oForwardX11=no",
136 "-w", HOSTNAME, "echo", "ok"], None, self.output_ok)
137 self._clush_t(["-o", "-oStrictHostKeyChecking=no", "-o",
138 "-oForwardX11=no", "-w", HOSTNAME, "echo", "ok"], None,
139 self.output_ok)
140 self._clush_t(["-o-oStrictHostKeyChecking=no", "-o-oForwardX11=no",
141 "-w", HOSTNAME, "echo", "ok"], None, self.output_ok)
142 self._clush_t(["-u", "30", "-w", HOSTNAME, "echo", "ok"], None,
143 self.output_ok)
144 self._clush_t(["-t", "30", "-u", "30", "-w", HOSTNAME, "echo", "ok"],
145 None, self.output_ok)
146
147 def test_005_ssh_options_tty(self):
148 """test clush (ssh options) [tty]"""
149 setattr(ClusterShell.CLI.Clush, '_f_user_interaction', True)
150 try:
151 self.test_004_ssh_options()
152 finally:
153 delattr(ClusterShell.CLI.Clush, '_f_user_interaction')
154
155 def test_006_output_gathering(self):
156 """test clush (output gathering)"""
157 self._clush_t(["-w", HOSTNAME, "-bL", "echo", "ok"], None,
158 self.output_ok)
159 self._clush_t(["-w", HOSTNAME, "-qbL", "echo", "ok"], None,
160 self.output_ok)
161 self._clush_t(["-w", HOSTNAME, "-BL", "echo", "ok"], None,
162 self.output_ok)
163 self._clush_t(["-w", HOSTNAME, "-qBL", "echo", "ok"], None,
164 self.output_ok)
165 self._clush_t(["-w", HOSTNAME, "-BLS", "echo", "ok"], None,
166 self.output_ok)
167 self._clush_t(["-w", HOSTNAME, "-qBLS", "echo", "ok"], None,
168 self.output_ok)
169
170 s = "%s: ok\n---------------\n%s\n---------------\nok\n" \
171 % (HOSTNAME, HOSTNAME)
172 self._clush_t(["-w", HOSTNAME, "-vb", "echo", "ok"], None,
173 s.encode())
174
175 def test_007_output_gathering_tty(self):
176 """test clush (output gathering) [tty]"""
177 setattr(ClusterShell.CLI.Clush, '_f_user_interaction', True)
178 try:
179 self.test_006_output_gathering()
180 finally:
181 delattr(ClusterShell.CLI.Clush, '_f_user_interaction')
182
183 def test_008_file_copy(self):
184 """test clush (file copy)"""
185 content = "%f" % time.time()
186 content = content.encode()
187 sf = make_temp_file(content)
188 self._clush_t(["-w", HOSTNAME, "-c", sf.name], None, b"")
189 sf.seek(0)
190 self.assertEqual(sf.read(), content)
191 # test --dest option
192 f2 = tempfile.NamedTemporaryFile()
193 self._clush_t(["-w", HOSTNAME, "-c", sf.name, "--dest", f2.name], None,
194 b"")
195 f2.seek(0)
196 self.assertEqual(f2.read(), content)
197 # test multi --dest (manual)
198 tdir = make_temp_dir()
199 sf2 = make_temp_file(b'second')
200 try:
201 f2 = tempfile.NamedTemporaryFile()
202 self._clush_t(["-w", HOSTNAME, "-c", sf.name, sf2.name, "--dest",
203 tdir.name],
204 None, b"")
205 with open(os.path.join(tdir.name, basename(sf.name)), 'rb') as chkf:
206 self.assertEqual(chkf.read(), content)
207 with open(os.path.join(tdir.name, basename(sf2.name)), 'rb') as chkf:
208 self.assertEqual(chkf.read(), b'second')
209 finally:
210 sf2.close()
211 tdir.cleanup()
212 # test multi --dest (auto)
213 tdir = make_temp_dir()
214 sf2 = make_temp_file(b'second', dir=tdir.name)
215 try:
216 f2 = tempfile.NamedTemporaryFile()
217 self._clush_t(["-w", HOSTNAME, "-c", sf.name, sf2.name], None,
218 b"")
219 sf.seek(0)
220 sf2.seek(0)
221 self.assertEqual(sf.read(), content)
222 self.assertEqual(sf2.read(), b'second')
223 finally:
224 sf2.close()
225 tdir.cleanup()
226 # test --user option
227 f2 = tempfile.NamedTemporaryFile()
228 self._clush_t(["--user", pwd.getpwuid(os.getuid())[0], "-w", HOSTNAME,
229 "--copy", sf.name, "--dest", f2.name], None, b"")
230 f2.seek(0)
231 self.assertEqual(f2.read(), content)
232 # test --rcopy
233 self._clush_t(["--user", pwd.getpwuid(os.getuid())[0], "-w", HOSTNAME,
234 "--rcopy", sf.name, "--dest", dirname(sf.name)],
235 None, b"")
236 f2.seek(0)
237 self.assertEqual(open("%s.%s" % (sf.name, HOSTNAME), 'rb').read(),
238 content)
239 # test --rcopy with implicit --dest
240 self._clush_t(["--user", pwd.getpwuid(os.getuid())[0], "-w", HOSTNAME,
241 "--rcopy", sf.name],
242 None, b"")
243 f2.seek(0)
244 self.assertEqual(open("%s.%s" % (sf.name, HOSTNAME), 'rb').read(),
245 content)
246
247 def test_009_file_copy_tty(self):
248 """test clush (file copy) [tty]"""
249 setattr(ClusterShell.CLI.Clush, '_f_user_interaction', True)
250 try:
251 self.test_008_file_copy()
252 finally:
253 delattr(ClusterShell.CLI.Clush, '_f_user_interaction')
254
255 @unittest.skipIf(HOSTNAME == 'localhost', "does not work with hostname set to 'localhost'")
256 def test_010_diff(self):
257 """test clush (diff)"""
258 self._clush_t(["-w", HOSTNAME, "--diff", "echo", "ok"], None, b"")
259 self._clush_t(["-w", "%s,localhost" % HOSTNAME, "--diff", "echo",
260 "ok"], None, b"")
261
262 @unittest.skipIf(HOSTNAME == 'localhost', "does not work with hostname set to 'localhost'")
263 def test_011_diff_tty(self):
264 """test clush (diff) [tty]"""
265 setattr(ClusterShell.CLI.Clush, '_f_user_interaction', True)
266 try:
267 self.test_010_diff()
268 finally:
269 delattr(ClusterShell.CLI.Clush, '_f_user_interaction')
270
271 @unittest.skipIf(HOSTNAME == 'localhost', "does not work with hostname set to 'localhost'")
272 def test_012_diff_null(self):
273 """test clush (diff w/o output)"""
274 rxs = r"^--- %s\n\+\+\+ localhost\n@@ -1(,1)? \+[01],0 @@\n-ok\n$" % HOSTNAME
275 self._clush_t(["-R", "exec", "-w", "%s,localhost" % HOSTNAME, "--diff",
276 'echo %h | egrep -q "^localhost$" || echo ok'],
277 None, re.compile(rxs.encode()))
278
279 def test_013_stdin(self):
280 """test clush (stdin)"""
281 self._clush_t(["-w", HOSTNAME, "sleep 1 && cat"], b"ok", self.output_ok)
282
283 s = "%s: ok\n%s: ok\n" % (HOSTNAME, HOSTNAME)
284 self._clush_t(["-w", HOSTNAME, "cat"], b"ok\nok", s.encode())
285 # write binary to stdin
286 s = "%s: foo bar\n" % HOSTNAME
287 self._clush_t(["-w", HOSTNAME, "gzip -d"],
288 codecs.decode(b'1f8b0800869a744f00034bcbcf57484a2ce2020027b4dd1308000000',
289 'hex'),
290 s.encode())
291
292 def test_015_stderr(self):
293 """test clush (stderr)"""
294 s = "%s: err\n" % HOSTNAME
295 self._clush_t(["-w", HOSTNAME, "echo err 1>&2"], None, b"", 0,
296 s.encode())
297 self._clush_t(["-b", "-w", HOSTNAME, "-q", "echo err 1>&2"], None, b"",
298 0, s.encode())
299 s = "---------------\n%s\n---------------\nerr\n" % HOSTNAME
300 self._clush_t(["-B", "-w", HOSTNAME, "-q", "echo err 1>&2"], None,
301 s.encode())
302
303 def test_016_stderr_tty(self):
304 """test clush (stderr) [tty]"""
305 setattr(ClusterShell.CLI.Clush, '_f_user_interaction', True)
306 try:
307 self.test_015_stderr()
308 finally:
309 delattr(ClusterShell.CLI.Clush, '_f_user_interaction')
310
311 @unittest.skipIf(HOSTNAME == 'localhost', "does not work with hostname set to 'localhost'")
312 def test_017_retcodes(self):
313 """test clush (retcodes)"""
314 s = "clush: %s: exited with exit code 1\n" % HOSTNAME
315 exp_err = s.encode()
316 self._clush_t(["-w", HOSTNAME, "/bin/false"], None, b"", 0, exp_err)
317 self._clush_t(["-w", HOSTNAME, "-b", "/bin/false"], None, b"", 0, exp_err)
318 self._clush_t(["-S", "-w", HOSTNAME, "/bin/false"], None, b"", 1, exp_err)
319 self._clush_t(["--maxrc", "-w", HOSTNAME, "/bin/false"], None, b"", 1, exp_err)
320 self._clush_t(["-O", "maxrc=yes", "-w", HOSTNAME, "/bin/false"], None,
321 b"", 1, exp_err)
322 # -O takes precedence over --maxrc
323 self._clush_t(["--maxrc", "-O", "maxrc=no", "-w", HOSTNAME, "/bin/false"], None,
324 b"", 0, exp_err)
325 self._clush_t(["-O", "maxrc=no", "--maxrc", "-w", HOSTNAME, "/bin/false"], None,
326 b"", 0, exp_err)
327 for i in (1, 2, 127, 128, 255):
328 s = "clush: %s: exited with exit code %d\n" % (HOSTNAME, i)
329 self._clush_t(["-S", "-w", HOSTNAME, "exit %d" % i], None, b"", i,
330 s.encode())
331 self._clush_t(["-v", "-w", HOSTNAME, "/bin/false"], None, b"", 0,
332 exp_err)
333
334 duo = str(NodeSet("%s,localhost" % HOSTNAME))
335 s = "clush: %s (%d): exited with exit code 1\n" % (duo, 2)
336 self._clush_t(["-w", duo, "-b", "/bin/false"], None, b"", 0, s.encode())
337 s = "clush: %s: exited with exit code 1\n" % duo
338 self._clush_t(["-w", duo, "-b", "-q", "/bin/false"], None, b"", 0,
339 s.encode())
340 s = "clush: %s (%d): exited with exit code 1\n" % (duo, 2)
341 self._clush_t(["-w", duo, "-S", "-b", "/bin/false"], None, b"", 1,
342 s.encode())
343 self._clush_t(["-w", duo, "-S", "-b", "-q", "/bin/false"], None, b"", 1)
344
345 @unittest.skipIf(HOSTNAME == 'localhost', "does not work with hostname set to 'localhost'")
346 def test_018_retcodes_tty(self):
347 """test clush (retcodes) [tty]"""
348 setattr(ClusterShell.CLI.Clush, '_f_user_interaction', True)
349 try:
350 self.test_017_retcodes()
351 finally:
352 delattr(ClusterShell.CLI.Clush, '_f_user_interaction')
353
354 def test_019_timeout(self):
355 """test clush (timeout)"""
356 s = "clush: %s: command timeout\n" % HOSTNAME
357 self._clush_t(["-w", HOSTNAME, "-u", "1", "sleep 3"], None, b"", 0,
358 s.encode())
359 self._clush_t(["-w", HOSTNAME, "-u", "1", "-b", "sleep 3"], None, b"",
360 0, s.encode())
361
362 def test_020_timeout_tty(self):
363 """test clush (timeout) [tty]"""
364 setattr(ClusterShell.CLI.Clush, '_f_user_interaction', True)
365 try:
366 self.test_019_timeout()
367 finally:
368 delattr(ClusterShell.CLI.Clush, '_f_user_interaction')
369
370 def test_021_file_copy_timeout(self):
371 """test clush file copy (timeout)"""
372 content = "%f" % time.time()
373 content = content.encode()
374 f = make_temp_file(content)
375 s = "clush: %s: command timeout\n" % HOSTNAME
376 self._clush_t(["-w", HOSTNAME, "-u", "0.01", "-c", f.name], None,
377 b"", 0, s.encode())
378
379 def test_022_file_copy_timeout_tty(self):
380 """test clush file copy (timeout) [tty]"""
381 setattr(ClusterShell.CLI.Clush, '_f_user_interaction', True)
382 try:
383 self.test_021_file_copy_timeout()
384 finally:
385 delattr(ClusterShell.CLI.Clush, '_f_user_interaction')
386
387 def test_023_load_workerclass(self):
388 """test _load_workerclass()"""
389 for name in ('rsh', 'ssh', 'pdsh'):
390 cls = ClusterShell.CLI.Clush._load_workerclass(name)
391 self.assertTrue(cls)
392
393 def test_024_load_workerclass_error(self):
394 """test _load_workerclass() bad use cases"""
395 func = ClusterShell.CLI.Clush._load_workerclass
396 # Bad module
397 self.assertRaises(ImportError, func, 'not_a_module')
398 # Worker module but not supported
399 self.assertRaises(AttributeError, func, 'worker')
400
401 def test_025_worker(self):
402 """test clush (worker)"""
403 self._clush_t(["-w", HOSTNAME, "--worker=ssh", "echo ok"], None,
404 self.output_ok, 0)
405 self._clush_t(["-w", HOSTNAME, "-R", "ssh", "echo ok"], None,
406 self.output_ok, 0)
407 # also test in debug mode...
408 # Warning: Python3 will display b'...' in debug mode
409 rxs = r"EXECCLIENT: echo ok\n%s: [b\\']{0,2}ok[']{0,1}\n%s: ok\n" \
410 % (HOSTNAME, HOSTNAME)
411 self._clush_t(["-w", HOSTNAME, "--worker=exec", "-d", "echo ok"], None,
412 re.compile(rxs.encode()), 0)
413 self._clush_t(["-w", HOSTNAME, "-R", "exec", "-d", "echo ok"], None,
414 re.compile(rxs.encode()), 0)
415
416 def test_026_keyboard_interrupt(self):
417 """test clush on keyboard interrupt"""
418 # Note: the scope of this test is still limited as we cannot force user
419 # interaction (as clush is launched by subprocess). For replicated
420 # observation, we use --nostdin and only check if Keyboard interrupt
421 # message is printed...
422
423 class KillerThread(threading.Thread):
424 def run(self):
425 time.sleep(1)
426 # replace later by process.send_signal() [py2.6+]
427 os.kill(self.pidkill, signal.SIGINT)
428
429 kth = KillerThread()
430 args = ["-w", HOSTNAME, "--worker=exec", "-q", "--nostdin", "-b",
431 "echo start; sleep 10"]
432 python_exec = basename(sys.executable or 'python')
433 process = Popen([python_exec, '-m', 'ClusterShell.CLI.Clush'] + args,
434 stderr=PIPE, stdout=PIPE, bufsize=0)
435 kth.pidkill = process.pid
436 kth.start()
437 stderr = process.communicate()[1]
438 self.assertEqual(stderr, b"Keyboard interrupt.\n")
439
440 def test_027_warn_shell_globbing_nodes(self):
441 """test clush warning on shell globbing (-w)"""
442 tdir = make_temp_dir()
443 tfile = open(os.path.join(tdir.name, HOSTNAME), "w")
444 curdir = os.getcwd()
445 try:
446 os.chdir(tdir.name)
447 s = b"Warning: using '-w %s' and local path '%s' exists, was it " \
448 b"expanded by the shell?\n" % (HOSTNAME.encode(), HOSTNAME.encode())
449 # Use regex to match start of stderr, allowing for additional warnings
450 self._clush_t(["-w", HOSTNAME, "echo", "ok"], None,
451 self.output_ok, 0, re.compile(re.escape(s)))
452 finally:
453 os.chdir(curdir)
454 tfile.close()
455 os.unlink(tfile.name)
456 tdir.cleanup()
457
458 def test_028_warn_shell_globbing_exclude(self):
459 """test clush warning on shell globbing (-x)"""
460 tdir = make_temp_dir()
461 tfile = open(os.path.join(tdir.name, HOSTNAME), "wb")
462 curdir = os.getcwd()
463 try:
464 os.chdir(tdir.name)
465 rxs = r"^Warning: using '-x %s' and local path " \
466 r"'%s' exists, was it expanded by the shell\?\n" \
467 % (HOSTNAME, HOSTNAME)
468 self._clush_t(["-S", "-w", "badhost,%s" % HOSTNAME, "-x", HOSTNAME,
469 "echo", "ok"], None, b"", 255,
470 re.compile(rxs.encode()))
471 finally:
472 os.chdir(curdir)
473 tfile.close()
474 os.unlink(tfile.name)
475 tdir.cleanup()
476
477 def test_029_hostfile(self):
478 """test clush --hostfile"""
479 f = make_temp_file(HOSTNAME.encode())
480 self._clush_t(["--hostfile", f.name, "echo", "ok"], None,
481 self.output_ok)
482 f2 = make_temp_file(HOSTNAME.encode())
483 self._clush_t(["--hostfile", f.name, "--hostfile", f2.name,
484 "echo", "ok"], None, self.output_ok)
485 self.assertRaises(OSError, self._clush_t,
486 ["--hostfile", "/I/do/NOT/exist", "echo", "ok"],
487 None, 1)
488
489 def test_030_config_options(self):
490 """test clush -O/--option"""
491 self._clush_t(["--option", "color=never", "-w", HOSTNAME, "echo", "ok"],
492 None, self.output_ok)
493 self._clush_t(["--option", "color=always", "-w", HOSTNAME, "echo",
494 "ok"], None, self.output_ok_color)
495 self._clush_t(["--option=color=never", "-w", HOSTNAME, "echo", "ok"],
496 None, self.output_ok)
497 self._clush_t(["--option=color=always", "-w", HOSTNAME, "echo", "ok"],
498 None, self.output_ok_color)
499 self._clush_t(["-O", "fd_max=220", "--option", "color=never", "-w",
500 HOSTNAME, "echo", "ok"], None, self.output_ok)
501 self._clush_t(["-O", "fd_max=220", "--option", "color=always", "-w",
502 HOSTNAME, "echo", "ok"], None, self.output_ok_color)
503 self._clush_t(["--option", "color=never", "-O", "fd_max=220", "-w",
504 HOSTNAME, "echo", "ok"], None, self.output_ok)
505 self._clush_t(["--option", "color=always", "-O", "fd_max=220", "-w",
506 HOSTNAME, "echo", "ok"], None, self.output_ok_color)
507 self._clush_t(["--option", "color=never", "-O", "fd_max=220", "-O",
508 "color=always", "-w", HOSTNAME, "echo", "ok"], None,
509 self.output_ok_color)
510 self._clush_t(["--option", "color=always", "-O", "fd_max=220", "-O",
511 "color=never", "-w", HOSTNAME, "echo", "ok"], None,
512 self.output_ok)
513
514 @unittest.skipIf(HOSTNAME == 'localhost', "does not work with hostname set to 'localhost'")
515 def test_031_progress(self):
516 """test clush -P/--progress"""
517 self._clush_t(["-w", HOSTNAME, "--progress", "echo", "ok"], None,
518 self.output_ok)
519 self._clush_t(["-w", HOSTNAME, "--progress", "sleep", "2"], None, b'', 0,
520 re.compile(r'clush: 0/1\r.*'.encode()))
521 self._clush_t(["-w", HOSTNAME, "--progress", "sleep", "2"], b'AAAAAAAA',
522 b'', 0, re.compile(r'clush: 0/1 write: \d B/s\r.*'.encode()))
523 self._clush_t(["-w", "%s,localhost" % HOSTNAME, "--progress", "sleep",
524 "2"], b'AAAAAAAAAAAAAA', b'', 0,
525 re.compile(r'clush: 0/2 write: \d+ B/s\r.*'.encode()))
526 self._clush_t(["-w", HOSTNAME, "-b", "--progress", "sleep", "2"],
527 None, b'', 0, re.compile(r'clush: 0/1\r.*'.encode()))
528 self._clush_t(["-w", HOSTNAME, "-b", "--progress", "sleep", "2"],
529 b'AAAAAAAAAAAAAAAA', b'', 0,
530 re.compile(r'clush: 0/1 write: \d+ B/s\r.*'.encode()))
531 # -q and --progress: explicit -q wins
532 self._clush_t(["-w", HOSTNAME, "--progress", "-q", "sleep", "2"], None,
533 b'', 0)
534 self._clush_t(["-w", HOSTNAME, "-b", "--progress", "-q", "sleep", "2"],
535 None, b'', 0, b'')
536 self._clush_t(["-w", HOSTNAME, "-b", "--progress", "-q", "sleep", "2"],
537 b'AAAAAAAAAAAAAAAA', b'', 0, b'')
538 # cover stderr output and --progress
539 s = "%s: bar\n" % HOSTNAME
540 err_rxs = r'%s: foo\nclush: 0/1\r.*' % HOSTNAME
541 self._clush_t(["-w", HOSTNAME, "--progress",
542 "echo foo >&2; echo bar; sleep 2"], None,
543 s.encode(), 0, re.compile(err_rxs.encode()))
544
545 @unittest.skipIf(which('pdsh') is None, "pdsh is not installed")
546 def test_032_worker_pdsh(self):
547 """test clush (worker pdsh)"""
548 # Warning: same as: echo -n | clush --worker=pdsh when launched from
549 # jenkins (not a tty), so we need --nostdin as pdsh worker doesn't
550 # support write
551 self._clush_t(["-w", HOSTNAME, "--worker=pdsh", "--nostdin",
552 "echo ok"], None, self.output_ok, 0)
553 # write not supported by pdsh worker
554 self.assertRaises(EngineClientNotSupportedError, self._clush_t,
555 ["-w", HOSTNAME, "-R", "pdsh", "cat"], b"bar", None, 1)
556
557 @unittest.skipIf(which('pdsh') is None, "pdsh is not installed")
558 def test_033_worker_pdsh_tty(self):
559 """test clush (worker pdsh) [tty]"""
560 setattr(ClusterShell.CLI.Clush, '_f_user_interaction', True)
561 try:
562 self._clush_t(["-w", HOSTNAME, "--worker=pdsh", "echo ok"],
563 None, self.output_ok, 0)
564 finally:
565 delattr(ClusterShell.CLI.Clush, '_f_user_interaction')
566
567 @unittest.skipIf(HOSTNAME == 'localhost', "does not work with hostname set to 'localhost'")
568 def test_034_pick(self):
569 """test clush --pick"""
570 rxs = r"^(localhost|%s): foo\n$" % HOSTNAME
571 self._clush_t(["-w", "%s,localhost" % HOSTNAME, "--pick", "1",
572 "echo foo"], None, re.compile(rxs.encode()))
573 rxs = r"^((localhost|%s): foo\n){2}$" % HOSTNAME
574 self._clush_t(["-w", "%s,localhost" % HOSTNAME, "--pick", "2",
575 "echo foo"], None, re.compile(rxs.encode()))
576
577 def test_035_sorted_line_mode(self):
578 """test clush (sorted line mode -L)"""
579 self._clush_t(["-w", HOSTNAME, "-L", "echo", "ok"], None,
580 self.output_ok)
581
582 # Issue #326
583 cmd = "bash -c 's=%h; n=${s//[!0-9]/}; if [[ $(expr $n %% 2) == 0 ]]; then " \
584 "echo foo; else echo bar; fi'"
585
586 self._clush_t(["-w", "cs[01-03]", "--worker=exec", "-L", cmd], None,
587 b'cs01: bar\ncs02: foo\ncs03: bar\n', 0)
588
589 def test_036_sorted_gather(self):
590 """test clush (CLI.Utils.bufnodeset_cmpkey)"""
591 # test 1st sort criteria: largest nodeset first
592 cmd = "bash -c 's=%h; n=${s//[!0-9]/}; if [[ $(expr $n %% 2) == 0 ]];" \
593 "then echo foo; else echo bar; fi'"
594
595 self._clush_t(["-w", "cs[01-03]", "--worker=exec", "-b", cmd], None,
596 b'---------------\ncs[01,03] (2)\n---------------\nbar\n'
597 b'---------------\ncs02\n---------------\nfoo\n', 0)
598
599 # test 2nd sort criteria: smaller node index first
600 cmd = "bash -c 's=%h; n=${s//[!0-9]/}; if [[ $(expr $n %% 2) == 0 ]];" \
601 "then echo bar; else echo foo; fi'"
602
603 self._clush_t(["-w", "cs[01-04]", "--worker=exec", "-b", cmd], None,
604 b'---------------\ncs[01,03] (2)\n---------------\nfoo\n'
605 b'---------------\ncs[02,04] (2)\n---------------\nbar\n',
606 0)
607
608 def test_037_nostdin(self):
609 """test clush (nostdin)"""
610 self._clush_t(["-n", "-w", HOSTNAME, "cat"], b"dummy", b"")
611 self._clush_t(["--nostdin", "-w", HOSTNAME, "cat"], b"dummy", b"")
612
613 def test_038_rlimits(self):
614 """test clush error with low fd_max"""
615 # These tests also cover pipe() fd cleanup handling code in
616 # fastsubprocess' Popen._gethandles(). All file descriptors should
617 # be properly cleaned.
618 #
619 # Each fork creates 3 FDs remaining in the parent process. We have
620 # two tests here with a different fd_max each time in order to raise
621 # the exception during stdout and stderr pipe creation.
622 # Depending on the current available FDs during the test, the two
623 # tests below might be reversed.
624 #
625 # test for error when creating stdout pipes:
626 # 99 used OK + 1 (stdin)
627 self.assertRaises(OSError, self._clush_t,
628 ["-N", "-R", "exec", "-w", 'foo[1-1000]', "-b",
629 "-f", "1000", "-O", "fd_max=100", "echo ok"],
630 None, b"ok\n")
631 #
632 # test for error when creating stderr pipes:
633 # 99 OK + 1 (stdin) + 1 (stdout)
634 self.assertRaises(OSError, self._clush_t,
635 ["-N", "-R", "exec", "-w", 'foo[1-1000]', "-b",
636 "-f", "1000", "-O", "fd_max=101", "echo ok"],
637 None, b"ok\n")
638
639 def test_039_conf_option(self):
640 """test clush --conf option"""
641 custf = make_temp_file(dedent("""
642 [Main]
643 node_count: no
644 """).encode())
645
646 # simple test that checks if "node_count:" no from custom conf file
647 # is taken into account
648
649 self._clush_t(["-b", "-R", "exec", "-w", "foo[1-10]", "echo ok"], b"",
650 b"---------------\nfoo[1-10] (10)\n---------------\nok\n")
651
652 self._clush_t(["--conf", custf.name, "-b", "-R", "exec", "-w",
653 "foo[1-10]", "echo ok"], b"",
654 b"---------------\nfoo[1-10]\n---------------\nok\n")
655
656 def test_040_stdin_eof(self):
657 """test clush (stdin eof)"""
658 # should not block if connection to stdin cannot be established
659 # or of --nostdin is specified
660 self._clush_t(["-w", HOSTNAME, "cat"], None, b'')
661 self._clush_t(["-w", HOSTNAME, "--nostdin", "cat"], None, b'')
662 setattr(ClusterShell.CLI.Clush, '_f_user_interaction', True)
663 try:
664 self._clush_t(["-w", HOSTNAME, "cat"], None, b'')
665 finally:
666 delattr(ClusterShell.CLI.Clush, '_f_user_interaction')
667
668 def test_041_outdir_errdir(self):
669 """test clush --outdir and --errdir"""
670 odir = make_temp_dir()
671 edir = make_temp_dir()
672 tofilepath = os.path.join(odir.name, HOSTNAME)
673 tefilepath = os.path.join(edir.name, HOSTNAME)
674 try:
675 self._clush_t(["-w", HOSTNAME, "--outdir", odir.name, "echo", "ok"],
676 None, self.output_ok)
677 self.assertTrue(os.path.isfile(tofilepath))
678 with open(tofilepath, "r") as f:
679 self.assertEqual(f.read(), "ok\n")
680 finally:
681 os.unlink(tofilepath)
682 try:
683 self._clush_t(["-w", HOSTNAME, "--errdir", edir.name, "echo", "ok", ">&2"],
684 None, None, 0, self.output_ok)
685 self.assertTrue(os.path.isfile(tefilepath))
686 with open(tefilepath, "r") as f:
687 self.assertEqual(f.read(), "ok\n")
688 finally:
689 os.unlink(tefilepath)
690 try:
691 serr = "%s: err\n" % HOSTNAME
692 self._clush_t(["-w", HOSTNAME, "--outdir", odir.name, "--errdir", edir.name,
693 "echo", "ok", ";", "echo", "err", ">&2"], None,
694 self.output_ok, 0, serr.encode())
695 self.assertTrue(os.path.isfile(tofilepath))
696 self.assertTrue(os.path.isfile(tefilepath))
697 with open(tofilepath, "r") as f:
698 self.assertEqual(f.read(), "ok\n")
699 with open(tefilepath, "r") as f:
700 self.assertEqual(f.read(), "err\n")
701 finally:
702 os.unlink(tofilepath)
703 os.unlink(tefilepath)
704 odir.cleanup()
705 edir.cleanup()
706
707 def test_042_command_prefix(self):
708 """test clush -O command_prefix"""
709 s = "%s: foobar\n" % HOSTNAME
710 self._clush_t(["-O", "command_prefix=echo", "-w", HOSTNAME, "foobar"],
711 None, s.encode())
712 self._clush_t(["-O", "command_prefix=echo", "--nostdin", "-w", HOSTNAME, "foobar"],
713 None, s.encode())
714
715 def test_043_password_prompt(self):
716 """test clush -O password_prompt"""
717 def ask_pass_mock():
718 return "passok"
719 ask_pass_save = ClusterShell.CLI.Clush.ask_pass
720 ClusterShell.CLI.Clush.ask_pass = ask_pass_mock
721 try:
722 s = "%s: passok\n" % HOSTNAME
723 expected = s.encode()
724 self._clush_t(["-O", "password_prompt=yes", "-w", HOSTNAME, "cat"],
725 None, expected)
726 self._clush_t(["-O", "password_prompt=yes", "-w", HOSTNAME, "cat"],
727 b"test\n", expected+('%s: test\n' % HOSTNAME).encode())
728 self._clush_t(["-O", "password_prompt=yes", "--nostdin", "-w", HOSTNAME, "cat"],
729 None, expected)
730 self._clush_t(["-O", "password_prompt=yes", "--nostdin", "-w", HOSTNAME, "cat"],
731 b"test\n", expected)
732 # write to stdin is not supported by pdsh worker
733 self.assertRaises(EngineClientNotSupportedError, self._clush_t,
734 ["-O", "password_prompt=yes", "-w", HOSTNAME, "-R", "pdsh", "cat"],
735 b"test stdin", expected, 1)
736 self.assertRaises(EngineClientNotSupportedError, self._clush_t,
737 ["--nostdin", "-O", "password_prompt=yes", "-w", HOSTNAME, "-R", "pdsh", "cat"],
738 b"test stdin", expected, 1)
739 finally:
740 ClusterShell.CLI.Clush.ask_pass = ask_pass_save
741
742 def test_044_command_prefix_and_password_prompt(self):
743 """test clush -O command_prefix and -O password_prompt"""
744 def ask_pass_mock():
745 return "passok"
746 ask_pass_save = ClusterShell.CLI.Clush.ask_pass
747 ClusterShell.CLI.Clush.ask_pass = ask_pass_mock
748 try:
749 s = "%s: passok\n" % HOSTNAME
750 expected = s.encode()
751 # using 'exec' command to simulate sudo-like behavior
752 self._clush_t(["-O", "command_prefix=exec", "-O", "password_prompt=yes", "-w", HOSTNAME, "cat"],
753 None, expected)
754 self._clush_t(["-O", "command_prefix=exec", "-O", "password_prompt=yes", "-w", HOSTNAME, "cat"],
755 b"test\n", expected+('%s: test\n' % HOSTNAME).encode())
756 self._clush_t(["-O", "command_prefix=exec", "-O", "password_prompt=yes", "--nostdin", "-w", HOSTNAME, "cat"],
757 None, expected)
758 self._clush_t(["-O", "command_prefix=exec", "-O", "password_prompt=yes", "--nostdin", "-w", HOSTNAME, "cat"],
759 b"test\n", expected)
760 # test password forwarding followed by stdin stream
761 s = "%s: test stdin\n" % HOSTNAME
762 expected += s.encode()
763 self._clush_t(["-O", "command_prefix=exec", "-O", "password_prompt=yes", "-w", HOSTNAME, "cat"],
764 b"test stdin\n", expected)
765 finally:
766 ClusterShell.CLI.Clush.ask_pass = ask_pass_save
767
768 def test_045_pipe_line_buffering(self):
769 """test clush stdout line buffering when piped (GH#597)"""
770 # Remote command emits 3 lines with a sleep between each. With the
771 # fix, lines arrive ~0.5s apart through the pipe. If clush stdout is
772 # block-buffered (the bug), all 3 arrive together at child exit.
773 python_exec = basename(sys.executable or 'python')
774 args = ['-w', HOSTNAME, '--worker=exec', '-q',
775 'for i in A B C; do echo $i; sleep 0.5; done']
776 with Popen([python_exec, '-m', 'ClusterShell.CLI.Clush'] + args,
777 stdout=PIPE, stderr=PIPE,
778 universal_newlines=True, bufsize=1) as process:
779 timestamps = []
780 t0 = time.monotonic()
781 for _line in process.stdout:
782 timestamps.append(time.monotonic() - t0)
783 process.wait(timeout=10)
784 self.assertEqual(len(timestamps), 3,
785 "expected 3 lines, got %d" % len(timestamps))
786 spread = timestamps[-1] - timestamps[0]
787 # Bug signature: spread ~0 (lines released together at clush exit).
788 # Fix signature: spread ~1s. 0.5s threshold = midpoint, equally far
789 # from both signals — generous for CI jitter.
790 self.assertGreater(spread, 0.5,
791 "lines arrived together (spread=%.3fs); "
792 "clush stdout looks block-buffered" % spread)
793
794 def test_046_axis(self):
795 """test clush --axis (fold gathered output along selected axis)"""
796 # 2D nodeset gathered locally via exec worker; all hosts emit the
797 # same output, so the folded header reflects the requested axis.
798 base = ["-R", "exec", "-w", "foo[1-2]-[1-2]", "-b", "echo test"]
799 fold_axis_save = DEFAULTS.fold_axis
800 try:
801 DEFAULTS.fold_axis = ()
802 # no --axis: fold along all axis (default)
803 self._clush_t(base, b"",
804 b"---------------\nfoo[1-2]-[1-2] (4)\n"
805 b"---------------\ntest\n")
806 # --axis=1: fold first dimension only
807 self._clush_t(["--axis=1"] + base, b"",
808 b"---------------\nfoo[1-2]-1,foo[1-2]-2 (4)\n"
809 b"---------------\ntest\n")
810 # --axis=2: fold second dimension only
811 self._clush_t(["--axis=2"] + base, b"",
812 b"---------------\nfoo1-[1-2],foo2-[1-2] (4)\n"
813 b"---------------\ntest\n")
814 # --axis=-1: fold last dimension only
815 self._clush_t(["--axis=-1"] + base, b"",
816 b"---------------\nfoo1-[1-2],foo2-[1-2] (4)\n"
817 b"---------------\ntest\n")
818 # 1D nodeset still folds normally with --axis=1
819 self._clush_t(["--axis=1", "-R", "exec", "-w", "node[1-4]", "-b",
820 "echo test"], b"",
821 b"---------------\nnode[1-4] (4)\n"
822 b"---------------\ntest\n")
823 finally:
824 DEFAULTS.fold_axis = fold_axis_save
825
826
827 class CLIClushTest_B_StdinFailure(unittest.TestCase):
828 """Unit test class for testing CLI/Clush.py and stdin failure"""
829
830 def setUp(self):
831 class BrokenStdinMock(object):
832 def isatty(self):
833 return False
834 def fileno(self):
835 raise IOError(errno.EINVAL, "Invalid argument")
836
837 sys.stdin = BrokenStdinMock()
838
839 def tearDown(self):
840 """cleanup all tasks"""
841 task_cleanup()
842 sys.stdin = sys.__stdin__
843
844 def _clush_t(self, args, stdin, expected_stdout, expected_rc=0,
845 expected_stderr=None):
846 CLI_main(self, main, ['clush'] + args, stdin, expected_stdout,
847 expected_rc, expected_stderr)
848
849 def test_100_broken_stdin(self):
850 """test clush with broken stdin"""
851 self._clush_t(["-w", HOSTNAME, "-v", "sleep 1"], None,
852 b"stdin: [Errno 22] Invalid argument\n", 0, b"")
853
854
855 class CLIClushTest_C_GroupsConf(unittest.TestCase):
856 """Unit test class for testing CLI/Clush.py with --groupsconf"""
857
858 def setUp(self):
859 self.gconff = make_temp_file(dedent("""
860 [Main]
861 default: global_default
862
863 [global_default]
864 map: echo example[1-100]
865 all: echo @foo,@bar,@moo
866 list: echo foo bar moo
867 """).encode())
868 set_std_group_resolver_config(self.gconff.name)
869
870 # passed to --groupsconf
871 self.custf = make_temp_file(dedent("""
872 [Main]
873 default: custom
874
875 [custom]
876 map: echo custom[7-42]
877 all: echo @selene,@artemis
878 list: echo selene artemis
879 """).encode())
880
881 def tearDown(self):
882 set_std_group_resolver(None)
883 self.gconff = None
884 self.custf = None
885
886 def _clush_t(self, args, stdin, expected_stdout, expected_rc=0,
887 expected_stderr=None):
888 CLI_main(self, main, ['clush'] + args, stdin, expected_stdout,
889 expected_rc, expected_stderr)
890
891 def test_200_groupsconf_option(self):
892 """test clush --groupsconf"""
893 self._clush_t(["-R", "exec", "-w", "@foo", "-bL", "echo ok"], None,
894 b"example[1-100]: ok\n", 0, b"")
895 self._clush_t(["--groupsconf", self.custf.name, "-R", "exec", "-w",
896 "@foo", "-bL", "echo ok"], None,
897 b"custom[7-42]: ok\n", 0, b"")
898
899
900 class CLIClushTest_D_StdinFIFO(unittest.TestCase):
901 """Unit test class for testing CLI/Clush.py when stdin is a named pipe"""
902
903 def setUp(self):
904 # Create fifo
905 self.fname = tempfile.mktemp()
906 os.mkfifo(self.fname)
907
908 # Launch write thread
909 class FIFOThread(threading.Thread):
910 def run(self):
911 fifo_wr = open(self.fname, "w")
912 fifo_wr.write("0123456789")
913 fifo_wr.close()
914
915 fifoth = FIFOThread()
916 fifoth.fname = self.fname
917 fifoth.start()
918
919 # Use read end of fifo as stdin
920 sys.stdin = open(self.fname, "r")
921
922 def tearDown(self):
923 """cleanup all tasks"""
924 sys.stdin.close()
925 os.unlink(self.fname)
926 task_cleanup()
927 sys.stdin = sys.__stdin__
928
929 def _clush_t(self, args, stdin, expected_stdout, expected_rc=0,
930 expected_stderr=None):
931 CLI_main(self, main, ['clush'] + args, stdin, expected_stdout,
932 expected_rc, expected_stderr)
933
934 def test_300_fifo_stdin(self):
935 """test clush with stdin is a fifo (read)"""
936 s = "%s: 0123456789\n" % HOSTNAME
937 self._clush_t(["-w", HOSTNAME, "-v", "cat"], None,
938 s.encode(), 0, b"")
939
940 def test_301_fifo_stdin(self):
941 """test clush with stdin is a fifo (not read)"""
942 s = "%s: ok\n" % HOSTNAME
943 self._clush_t(["-w", HOSTNAME, "-v", "echo ok"], None,
944 s.encode(), 0, b"")
945
946
947 class CLIClushTest_E_Topology(unittest.TestCase):
948 """Unit test class for testing CLI/Clush.py with --topology"""
949
950 def setUp(self):
951 self.topofile = make_temp_file(dedent("""
952 [routes]
953 %s: localhost
954 localhost: remote-node"""% HOSTNAME).encode())
955
956 def tearDown(self):
957 self.topofile = None
958
959 def _clush_t(self, args, stdin, expected_stdout, expected_rc=0,
960 expected_stderr=None):
961 CLI_main(self, main, ['clush'] + args, stdin, expected_stdout,
962 expected_rc, expected_stderr)
963
964 @unittest.skipIf(HOSTNAME == 'localhost', "does not work with hostname set to 'localhost'")
965 def test_300_topology(self):
966 """test clush --topology"""
967 # GH#560: to detect set!=NodeSet for gwtargets
968 self._clush_t(["--topology", self.topofile.name,
969 "-w", "remote-node", "-b", "-v", "sleep 1; echo ok"], None, b"", 0, b"")