Debian Codegraph @

tests/TreeGatewayTest.py

raw symbols SCIP
1 """
2 Unit test for ClusterShell.Gateway
3 """
4
5 import base64
6 import logging
7 import os
8 import re
9 import select
10 import unittest
11 import xml.sax
12
13 from ClusterShell import __version__
14 from ClusterShell.Communication import ConfigurationMessage, ControlMessage, \
15 StdOutMessage, StdErrMessage, RetcodeMessage, ACKMessage, ErrorMessage, \
16 TimeoutMessage, StartMessage, EndMessage, XMLReader
17 from ClusterShell.Gateway import GatewayChannel
18 from ClusterShell.NodeSet import NodeSet
19 from ClusterShell.Propagation import PropagationChannel
20 from ClusterShell.Task import Task, task_self
21 from ClusterShell.Topology import TopologyError, TopologyGraph
22 from ClusterShell.Worker.Tree import TreeWorker
23 from ClusterShell.Worker.Worker import StreamWorker
24
25 from .TLib import HOSTNAME
26
27 # enable live DEBUG logging when running the tests
28 logging.basicConfig(level=logging.DEBUG)
29
30 # max time (secs) to wait for a gateway reply before failing the test
31 RECV_TIMEOUT = 30
32
33
34 class Gateway(object):
35 """Gateway special test class.
36
37 Initialize a GatewayChannel through a R/W StreamWorker like a real
38 remote ClusterShell Gateway but:
39 - using pipes to communicate,
40 - running on a dedicated task/thread.
41 """
42
43 def __init__(self):
44 """init Gateway bound objects"""
45 self.task = Task()
46 self.channel = GatewayChannel(self.task)
47 self.worker = StreamWorker(handler=self.channel)
48 # create communication pipes
49 self.pipe_stdin = os.pipe()
50 self.pipe_stdout = os.pipe()
51 # avoid nonblocking flag as we want recv/read() to block
52 self.worker.set_reader(self.channel.SNAME_READER,
53 self.pipe_stdin[0])
54 self.worker.set_writer(self.channel.SNAME_WRITER,
55 self.pipe_stdout[1], retain=False)
56 self.task.schedule(self.worker)
57 self.task.resume()
58
59 def send(self, msg):
60 """send msg (bytes) to pseudo stdin"""
61 os.write(self.pipe_stdin[1], msg + b'\n')
62
63 def send_str(self, msgstr):
64 """send msg (string) to pseudo stdin"""
65 self.send(msgstr.encode())
66
67 def recv(self):
68 """recv buf from pseudo stdout (blocking call with timeout)"""
69 if not select.select([self.pipe_stdout[0]], [], [], RECV_TIMEOUT)[0]:
70 raise RuntimeError("no gateway reply after %ds" % RECV_TIMEOUT)
71 return os.read(self.pipe_stdout[0], 4096)
72
73 def wait(self):
74 """wait for task/thread termination"""
75 # can be blocked indefinitely if StreamWorker doesn't complete
76 self.task.join()
77
78 def close(self):
79 """close parent fds"""
80 os.close(self.pipe_stdout[0])
81 os.close(self.pipe_stdin[1])
82
83 def destroy(self):
84 """abort task/thread"""
85 self.task.abort(kill=True)
86
87
88 class TreeGatewayBaseTest(unittest.TestCase):
89 """base test class"""
90
91 def setUp(self):
92 """setup gateway and topology for each test"""
93 # gateway
94 self.gateway = Gateway()
95 self.chan = self.gateway.channel
96 # topology
97 graph = TopologyGraph()
98 graph.add_route(NodeSet(HOSTNAME), NodeSet('n[1-2]'))
99 graph.add_route(NodeSet('n1'), NodeSet('n[10-49]'))
100 graph.add_route(NodeSet('n2'), NodeSet('n[50-89]'))
101 self.topology = graph.to_tree(HOSTNAME)
102 # xml parser with Communication.XMLReader as content handler
103 self.xml_reader = XMLReader()
104 self.parser = xml.sax.make_parser(["IncrementalParser"])
105 self.parser.setContentHandler(self.xml_reader)
106
107 def tearDown(self):
108 """destroy gateway after each test"""
109 self.gateway.destroy()
110 self.gateway = None
111
112 #
113 # Send to GW
114 #
115 def channel_send_start(self):
116 """send starting channel tag"""
117 self.gateway.send_str('<channel version="%s">' % __version__)
118
119 def channel_send_stop(self):
120 """send channel ending tag"""
121 self.gateway.send_str("</channel>")
122
123 def channel_send_cfg(self, gateway):
124 """send configuration part of channel"""
125 # code snippet from PropagationChannel.start()
126 cfg = ConfigurationMessage(gateway)
127 cfg.data_encode(self.topology)
128 self.gateway.send(cfg.xml())
129
130 #
131 # Receive from GW
132 #
133 def assert_isinstance(self, msg, msg_class):
134 """helper to check a message instance"""
135 self.assertTrue(isinstance(msg, msg_class),
136 "%s is not a %s" % (type(msg), msg_class))
137
138 def _recvxml(self):
139 while not self.xml_reader.msg_available():
140 xml_msg = self.gateway.recv()
141 if len(xml_msg) == 0:
142 self.parser.close()
143 break
144 self.assertTrue(type(xml_msg) is bytes)
145 self.parser.feed(xml_msg)
146 if hasattr(self.parser, 'flush'): # >=3.13 and backports
147 self.parser.flush()
148
149 return self.xml_reader.pop_msg()
150
151 def recvxml(self, expected_msg_class=None):
152 msg = self._recvxml()
153 if expected_msg_class is None:
154 self.assertEqual(msg, None)
155 else:
156 self.assert_isinstance(msg, expected_msg_class)
157 return msg
158
159
160 class TreeGatewayTest(TreeGatewayBaseTest):
161
162 def test_basic_noop(self):
163 """test gateway channel open/close"""
164 self.channel_send_start()
165 self.recvxml(StartMessage)
166 self.assertEqual(self.chan.opened, True)
167 self.assertEqual(self.chan.setup, False)
168
169 self.channel_send_stop()
170 self.recvxml(EndMessage)
171 # ending tag should abort gateway worker without delay
172 self.gateway.wait()
173 self.gateway.close()
174
175 def test_channel_err_dup(self):
176 """test gateway channel duplicate tags"""
177 self.channel_send_start()
178 msg = self.recvxml(StartMessage)
179 self.assertEqual(self.chan.opened, True)
180 self.assertEqual(self.chan.setup, False)
181
182 # send an unexpected second channel tag
183 self.channel_send_start()
184 msg = self.recvxml(ErrorMessage)
185 self.assertEqual(msg.type, 'ERR')
186 reason = 'unexpected message: Message CHA '
187 self.assertEqual(msg.reason[:len(reason)], reason)
188
189 # gateway should terminate channel session
190 msg = self.recvxml(EndMessage)
191 self.gateway.wait()
192 self.gateway.close()
193
194 def _check_channel_err(self, sendmsg, errback, openchan=True,
195 setupchan=False):
196 """helper to ease test of erroneous messages sent to gateway"""
197 if openchan:
198 self.channel_send_start()
199 msg = self.recvxml(StartMessage)
200 self.assertEqual(self.chan.opened, True)
201 self.assertEqual(self.chan.setup, False)
202
203 if setupchan:
204 # send channel configuration
205 self.channel_send_cfg('n1')
206 msg = self.recvxml(ACKMessage)
207 self.assertEqual(self.chan.setup, True)
208
209 # send the erroneous message and test gateway reply
210 self.gateway.send_str(sendmsg)
211 msg = self.recvxml(ErrorMessage)
212 self.assertEqual(msg.type, 'ERR')
213 try:
214 if not errback.search(msg.reason):
215 self.assertFalse(msg.reason)
216 except AttributeError:
217 # not a regex
218 self.assertEqual(msg.reason, errback)
219
220 # gateway should terminate channel session
221 if openchan:
222 msg = self.recvxml(EndMessage)
223 self.assertEqual(msg.type, 'END')
224 else:
225 self.recvxml()
226
227 # gateway task should exit properly
228 self.gateway.wait()
229 self.gateway.close()
230
231 def test_err_start_with_ending_tag(self):
232 """test gateway missing opening channel tag"""
233 self._check_channel_err('</channel>',
234 'Parse error: not well-formed (invalid token)',
235 openchan=False)
236
237 def test_err_channel_end_msg(self):
238 """test gateway channel missing opening message tag"""
239 self._check_channel_err('</message>',
240 'Parse error: mismatched tag')
241
242 def test_err_channel_end_msg_setup(self):
243 """test gateway channel missing opening message tag (setup)"""
244 self._check_channel_err('</message>',
245 'Parse error: mismatched tag',
246 setupchan=True)
247
248 def test_err_unknown_tag(self):
249 """test gateway unknown tag"""
250 self._check_channel_err('<foobar></footbar>',
251 'Invalid starting tag foobar',
252 openchan=False)
253
254 def test_channel_err_unknown_tag(self):
255 """test gateway unknown tag in channel"""
256 self._check_channel_err('<foo></foo>', 'Invalid starting tag foo')
257
258 def test_channel_err_unknown_tag_setup(self):
259 """test gateway unknown tag in channel (setup)"""
260 self._check_channel_err('<foo></foo>',
261 'Invalid starting tag foo',
262 setupchan=True)
263
264 def test_err_unknown_msg(self):
265 """test gateway unknown message"""
266 self._check_channel_err('<message msgid="24" type="ABC"></message>',
267 'Unknown message type ABC',
268 openchan=False)
269
270 def test_channel_err_unknown_msg(self):
271 """test gateway channel unknown message"""
272 self._check_channel_err('<message msgid="24" type="ABC"></message>',
273 'Unknown message type ABC')
274
275 def test_channel_err_no_type_msg(self):
276 """test gateway channel message with no type"""
277 self._check_channel_err('<message msgid="24"></message>',
278 'Unknown message with no type')
279
280 def test_channel_err_empty_type_msg(self):
281 """test gateway channel message with empty type"""
282 self._check_channel_err('<message msgid="24" type=""></message>',
283 'Unknown message with no type')
284
285 def test_err_xml_malformed(self):
286 """test gateway malformed xml message"""
287 self._check_channel_err('<message type="ABC"</message>',
288 'Parse error: not well-formed (invalid token)',
289 openchan=False)
290
291 def test_channel_err_xml_malformed(self):
292 """test gateway channel malformed xml message"""
293 self._check_channel_err('<message type="ABC"</message>',
294 'Parse error: not well-formed (invalid token)')
295
296 def test_channel_err_xml_malformed_setup(self):
297 """test gateway channel malformed xml message"""
298 self._check_channel_err('<message type="ABC"</message>',
299 'Parse error: not well-formed (invalid token)',
300 setupchan=True)
301
302 def test_channel_err_xml_bad_char(self):
303 """test gateway channel malformed xml message (bad chars)"""
304 self._check_channel_err('\x11<message type="ABC"></message>',
305 'Parse error: not well-formed (invalid token)')
306
307 def test_channel_err_missingattr(self):
308 """test gateway channel message bad attributes"""
309 self._check_channel_err(
310 '<message msgid="24" nodes="foo" retcode="4" type="RET"></message>',
311 'Invalid "message" attributes: missing key "srcid"')
312
313 def test_channel_err_unexpected(self):
314 """test gateway channel unexpected message"""
315 self._check_channel_err(
316 '<message type="ACK" ack="2" msgid="2"></message>',
317 re.compile(r'unexpected message: Message ACK \(.*ack: 2.*\)'))
318
319 def test_channel_err_cfg_missing_gw(self):
320 """test gateway channel message missing gateway nodename"""
321 self._check_channel_err(
322 '<message msgid="337" type="CFG">DUMMY</message>',
323 'Invalid "message" attributes: missing key "gateway"')
324
325 def test_channel_err_missing_pl(self):
326 """test gateway channel message missing payload"""
327 self._check_channel_err(
328 '<message msgid="14" type="CFG" gateway="n1"></message>',
329 re.compile(r'Message CFG has an invalid payload'))
330
331 def test_channel_err_unexpected_pl(self):
332 """test gateway channel message unexpected payload"""
333 self._check_channel_err(
334 '<message msgid="14" type="ERR" reason="test">FOO</message>',
335 'Got unexpected payload for Message ERR', setupchan=True)
336
337 def test_channel_err_badenc_b2a_pl(self):
338 """test gateway channel message badly encoded payload (base64)"""
339 # Generate TypeError (py2) or binascii.Error (py3)
340 self._check_channel_err(
341 '<message msgid="14" type="CFG" gateway="n1">bar</message>',
342 re.compile(r'Message CFG has an invalid payload'))
343
344 def test_channel_err_badenc_pickle_pl(self):
345 """test gateway channel message badly encoded payload (pickle)"""
346 # Generate pickle error
347 self._check_channel_err(
348 '<message msgid="14" type="CFG" gateway="n1">barm</message>',
349 re.compile(r'Message CFG has an invalid payload'))
350
351 def test_channel_err_pickle_proto_pl(self):
352 """test gateway channel message payload with unknown pickle protocol"""
353 # Generate ValueError (unsupported pickle protocol: 7)
354 payload = base64.b64encode(b'\x80\x07spam').decode()
355 self._check_channel_err(
356 '<message msgid="14" type="CFG" gateway="n1">%s</message>'
357 % payload,
358 re.compile(r'Message CFG has an invalid payload'))
359
360 def test_channel_basic_abort(self):
361 """test gateway channel aborted while opened"""
362 self.channel_send_start()
363 self.recvxml(StartMessage)
364 self.assertEqual(self.chan.opened, True)
365 self.assertEqual(self.chan.setup, False)
366 self.gateway.close()
367 self.gateway.wait()
368
369 def _check_channel_ctl_shell(self, command, target, stderr, remote,
370 reply_msg_class, reply_pattern,
371 write_buf=None, timeout=-1, replycnt=1,
372 reply_rc=0):
373 """helper to check channel shell action"""
374 self.channel_send_start()
375 msg = self.recvxml(StartMessage)
376 self.channel_send_cfg('n1')
377 msg = self.recvxml(ACKMessage)
378
379 # prepare a remote shell command request...
380 workertree = TreeWorker(nodes=target, handler=None, timeout=timeout,
381 command=command)
382 # code snippet from PropagationChannel.shell()
383 ctl = ControlMessage(id(workertree))
384 ctl.action = 'shell'
385 ctl.target = NodeSet(target)
386
387 info = task_self()._info.copy()
388 info['debug'] = False
389
390 ctl_data = {
391 'cmd': command,
392 'invoke_gateway': workertree.invoke_gateway,
393 'taskinfo': info,
394 'stderr': stderr,
395 'timeout': timeout,
396 'remote': remote
397 }
398 ctl.data_encode(ctl_data)
399 self.gateway.send(ctl.xml())
400
401 self.recvxml(ACKMessage)
402
403 if write_buf:
404 ctl = ControlMessage(id(workertree))
405 ctl.action = 'write'
406 ctl.target = NodeSet(target)
407 ctl_data = {
408 'buf': write_buf,
409 }
410 # Send write message
411 ctl.data_encode(ctl_data)
412 self.gateway.send(ctl.xml())
413 self.recvxml(ACKMessage)
414
415 # Send EOF message
416 ctl = ControlMessage(id(workertree))
417 ctl.action = 'eof'
418 ctl.target = NodeSet(target)
419 self.gateway.send(ctl.xml())
420 self.recvxml(ACKMessage)
421
422 while replycnt > 0:
423 msg = self.recvxml(reply_msg_class)
424 replycnt -= len(NodeSet(msg.nodes))
425 self.assertTrue(msg.nodes in ctl.target)
426 if msg.has_payload or reply_pattern:
427 msg_data = msg.data_decode()
428 try:
429 if not reply_pattern.search(msg_data):
430 self.assertEqual(msg.data, reply_pattern,
431 'Pattern "%s" not found in data="%s"'
432 % (reply_pattern.pattern, msg_data))
433 except AttributeError:
434 # not a regexp
435 self.assertEqual(msg_data, reply_pattern)
436
437 if timeout <= 0:
438 msg = self.recvxml(RetcodeMessage)
439 self.assertEqual(msg.retcode, reply_rc)
440
441 self.channel_send_stop()
442 self.gateway.wait()
443 self.gateway.close()
444
445 def test_channel_ctl_shell_local1(self):
446 """test gateway channel shell stdout (stderr=False remote=False)"""
447 self._check_channel_ctl_shell("echo ok", "n10", False, False,
448 StdOutMessage, b"ok")
449
450 def test_channel_ctl_shell_local2(self):
451 """test gateway channel shell stdout (stderr=True remote=False)"""
452 self._check_channel_ctl_shell("echo ok", "n10", True, False,
453 StdOutMessage, b"ok")
454
455 def test_channel_ctl_shell_local3(self):
456 """test gateway channel shell stderr (stderr=True remote=False)"""
457 self._check_channel_ctl_shell("echo ok >&2", "n10", True, False,
458 StdErrMessage, b"ok")
459
460 def test_channel_ctl_shell_mlocal1(self):
461 """test gateway channel shell multi (remote=False)"""
462 self._check_channel_ctl_shell("echo ok", "n[10-49]", True, False,
463 StdOutMessage, b"ok", replycnt=40)
464
465 def test_channel_ctl_shell_mlocal2(self):
466 """test gateway channel shell multi stderr (remote=False)"""
467 self._check_channel_ctl_shell("echo ok 1>&2", "n[10-49]", True, False,
468 StdErrMessage, b"ok", replycnt=40)
469
470 def test_channel_ctl_shell_mlocal3(self):
471 """test gateway channel shell multi placeholder (remote=False)"""
472 self._check_channel_ctl_shell('echo node %h rank %n', "n[10-29]", True,
473 False, StdOutMessage,
474 re.compile(br"node n\d+ rank \d+"),
475 replycnt=20)
476
477 def test_channel_ctl_shell_remote1(self):
478 """test gateway channel shell stdout (stderr=False remote=True)"""
479 self._check_channel_ctl_shell("echo ok", "n10", False, True,
480 StdOutMessage,
481 re.compile(b"(Could not resolve hostname|"
482 b"Name or service not known)"),
483 reply_rc=255)
484
485 def test_channel_ctl_shell_remote2(self):
486 """test gateway channel shell stdout (stderr=True remote=True)"""
487 self._check_channel_ctl_shell("echo ok", "n10", True, True,
488 StdErrMessage,
489 re.compile(b"(Could not resolve hostname|"
490 b"Name or service not known)"),
491 reply_rc=255)
492
493 def test_channel_ctl_shell_timeo1(self):
494 """test gateway channel shell timeout"""
495 self._check_channel_ctl_shell("sleep 10", "n10", False, False,
496 TimeoutMessage, None, timeout=0.5)
497
498 def test_channel_ctl_shell_wrloc1(self):
499 """test gateway channel write (stderr=False remote=False)"""
500 self._check_channel_ctl_shell("cat", "n10", False, False,
501 StdOutMessage, b"ok", write_buf=b"ok\n")
502
503 def test_channel_ctl_shell_wrloc2(self):
504 """test gateway channel write (stderr=True remote=False)"""
505 self._check_channel_ctl_shell("cat", "n10", True, False,
506 StdOutMessage, b"ok", write_buf=b"ok\n")
507
508 def test_channel_ctl_shell_mwrloc1(self):
509 """test gateway channel write multi (remote=False)"""
510 self._check_channel_ctl_shell("cat", "n[10-49]", True, False,
511 StdOutMessage, b"ok", write_buf=b"ok\n")
512
513
514 class TreeMessageTest(unittest.TestCase):
515 """test tree communication messages (no gateway needed)"""
516
517 def test_msg_pickle_protocol(self):
518 """test message payload pickle protocol pin (wire format)"""
519 msg = ConfigurationMessage('n1')
520 msg.data_encode({'foo': 'bar'})
521 raw = base64.b64decode(msg.data)
522 # pickle protocol 2+ starts with PROTO opcode then protocol number
523 self.assertEqual(raw[0:1], b'\x80')
524 self.assertLessEqual(bytearray(raw)[1], 4) # bytearray for py2 compat
525 self.assertEqual(msg.data_decode(), {'foo': 'bar'})
526
527
528 class ChannelWorkerStub(object):
529 """stub channel worker for head-side channel tests"""
530
531 def __init__(self):
532 self.aborted = False
533
534 def write(self, buf, sname=None):
535 return len(buf)
536
537 def abort(self):
538 self.aborted = True
539
540
541 class MetaWorkerStub(object):
542 """stub metaworker recording remote node messages"""
543
544 def __init__(self):
545 self.msglines = []
546
547 def _on_remote_node_msgline(self, node, msg, sname, gateway):
548 self.msglines.append((node, msg, sname, gateway))
549
550
551 class TreeHeadChannelErrorTest(unittest.TestCase):
552 """test head-side (initiator) channel errors (no gateway needed)"""
553
554 def setUp(self):
555 self.chan = PropagationChannel(task_self(), 'gw1')
556 self.chan.worker = ChannelWorkerStub()
557 self.mw = MetaWorkerStub()
558 self.chan.workers[id(self.mw)] = self.mw
559 # gateway greeting opens the channel
560 self.chan.ev_read(self.chan.worker, 'gw1', self.chan.SNAME_READER,
561 ('<channel version="%s">' % __version__).encode())
562 self.assertTrue(self.chan.opened)
563
564 def test_head_channel_err_invalid_tag(self):
565 """test head channel invalid tag reported as stderr"""
566 self.chan.ev_read(self.chan.worker, 'gw1', self.chan.SNAME_READER,
567 b'<foo></foo>')
568 [(node, msg, sname, gateway)] = self.mw.msglines
569 self.assertEqual(node, 'gw1')
570 self.assertEqual(msg, b'Invalid starting tag foo')
571 self.assertEqual(sname, 'stderr')
572 self.assertEqual(gateway, 'gw1')
573 # fatal channel error: channel must be closed
574 self.assertTrue(self.chan.worker.aborted)
575 self.assertFalse(self.chan.opened)
576
577 def test_head_channel_err_parse_error(self):
578 """test head channel parse error reported as stderr"""
579 self.chan.ev_read(self.chan.worker, 'gw1', self.chan.SNAME_READER,
580 b'<message type="ABC"</message>')
581 [(node, msg, sname, gateway)] = self.mw.msglines
582 self.assertEqual(node, 'gw1')
583 self.assertTrue(isinstance(msg, bytes))
584 self.assertIn(b'not well-formed', msg)
585 self.assertEqual(sname, 'stderr')
586 self.assertEqual(gateway, 'gw1')
587 # fatal channel error: channel must be closed
588 self.assertTrue(self.chan.worker.aborted)
589 self.assertFalse(self.chan.opened)
590
591 def test_head_channel_gw_error_before_setup(self):
592 """test gateway error before setup reported as stderr"""
593 self.chan.ev_read(self.chan.worker, 'gw1', self.chan.SNAME_READER,
594 b'<message type="ERR" msgid="0" reason="Message CFG '
595 b'has an invalid payload (unsupported pickle '
596 b'protocol: 5)"></message>')
597 [(node, msg, sname, gateway)] = self.mw.msglines
598 self.assertEqual(node, 'gw1')
599 self.assertEqual(msg, b'Message CFG has an invalid payload'
600 b' (unsupported pickle protocol: 5)')
601 self.assertEqual(sname, 'stderr')
602 self.assertEqual(gateway, 'gw1')
603
604 def test_head_channel_gw_error_empty_reason(self):
605 """test gateway error with empty reason reported as empty line"""
606 self.chan.ev_read(self.chan.worker, 'gw1', self.chan.SNAME_READER,
607 b'<message type="ERR" msgid="0" reason=""></message>')
608 self.assertEqual(self.mw.msglines, [('gw1', b'', 'stderr', 'gw1')])
609
610 def test_head_channel_gw_error_after_setup(self):
611 """test gateway error after setup raises TopologyError"""
612 # gateway ACK completes channel setup
613 self.chan.ev_read(self.chan.worker, 'gw1', self.chan.SNAME_READER,
614 b'<message type="ACK" msgid="0" ack="0"></message>')
615 self.assertTrue(self.chan.setup)
616 self.assertRaises(TopologyError, self.chan.ev_read, self.chan.worker,
617 'gw1', self.chan.SNAME_READER,
618 b'<message type="ERR" msgid="1" reason="bad news">'
619 b'</message>')
620 self.assertEqual(self.mw.msglines, [])