protocol.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. import asyncio
  2. from contextlib import contextmanager
  3. import os
  4. import socket
  5. from tempfile import TemporaryDirectory
  6. import avocado
  7. from qemu.aqmp import ConnectError, Runstate
  8. from qemu.aqmp.protocol import AsyncProtocol, StateError
  9. from qemu.aqmp.util import asyncio_run, create_task
  10. class NullProtocol(AsyncProtocol[None]):
  11. """
  12. NullProtocol is a test mockup of an AsyncProtocol implementation.
  13. It adds a fake_session instance variable that enables a code path
  14. that bypasses the actual connection logic, but still allows the
  15. reader/writers to start.
  16. Because the message type is defined as None, an asyncio.Event named
  17. 'trigger_input' is created that prohibits the reader from
  18. incessantly being able to yield None; this event can be poked to
  19. simulate an incoming message.
  20. For testing symmetry with do_recv, an interface is added to "send" a
  21. Null message.
  22. For testing purposes, a "simulate_disconnection" method is also
  23. added which allows us to trigger a bottom half disconnect without
  24. injecting any real errors into the reader/writer loops; in essence
  25. it performs exactly half of what disconnect() normally does.
  26. """
  27. def __init__(self, name=None):
  28. self.fake_session = False
  29. self.trigger_input: asyncio.Event
  30. super().__init__(name)
  31. async def _establish_session(self):
  32. self.trigger_input = asyncio.Event()
  33. await super()._establish_session()
  34. async def _do_start_server(self, address, ssl=None):
  35. if self.fake_session:
  36. self._accepted = asyncio.Event()
  37. self._set_state(Runstate.CONNECTING)
  38. await asyncio.sleep(0)
  39. else:
  40. await super()._do_start_server(address, ssl)
  41. async def _do_accept(self):
  42. if self.fake_session:
  43. self._accepted = None
  44. else:
  45. await super()._do_accept()
  46. async def _do_connect(self, address, ssl=None):
  47. if self.fake_session:
  48. self._set_state(Runstate.CONNECTING)
  49. await asyncio.sleep(0)
  50. else:
  51. await super()._do_connect(address, ssl)
  52. async def _do_recv(self) -> None:
  53. await self.trigger_input.wait()
  54. self.trigger_input.clear()
  55. def _do_send(self, msg: None) -> None:
  56. pass
  57. async def send_msg(self) -> None:
  58. await self._outgoing.put(None)
  59. async def simulate_disconnect(self) -> None:
  60. """
  61. Simulates a bottom-half disconnect.
  62. This method schedules a disconnection but does not wait for it
  63. to complete. This is used to put the loop into the DISCONNECTING
  64. state without fully quiescing it back to IDLE. This is normally
  65. something you cannot coax AsyncProtocol to do on purpose, but it
  66. will be similar to what happens with an unhandled Exception in
  67. the reader/writer.
  68. Under normal circumstances, the library design requires you to
  69. await on disconnect(), which awaits the disconnect task and
  70. returns bottom half errors as a pre-condition to allowing the
  71. loop to return back to IDLE.
  72. """
  73. self._schedule_disconnect()
  74. class LineProtocol(AsyncProtocol[str]):
  75. def __init__(self, name=None):
  76. super().__init__(name)
  77. self.rx_history = []
  78. async def _do_recv(self) -> str:
  79. raw = await self._readline()
  80. msg = raw.decode()
  81. self.rx_history.append(msg)
  82. return msg
  83. def _do_send(self, msg: str) -> None:
  84. assert self._writer is not None
  85. self._writer.write(msg.encode() + b'\n')
  86. async def send_msg(self, msg: str) -> None:
  87. await self._outgoing.put(msg)
  88. def run_as_task(coro, allow_cancellation=False):
  89. """
  90. Run a given coroutine as a task.
  91. Optionally, wrap it in a try..except block that allows this
  92. coroutine to be canceled gracefully.
  93. """
  94. async def _runner():
  95. try:
  96. await coro
  97. except asyncio.CancelledError:
  98. if allow_cancellation:
  99. return
  100. raise
  101. return create_task(_runner())
  102. @contextmanager
  103. def jammed_socket():
  104. """
  105. Opens up a random unused TCP port on localhost, then jams it.
  106. """
  107. socks = []
  108. try:
  109. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  110. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  111. sock.bind(('127.0.0.1', 0))
  112. sock.listen(1)
  113. address = sock.getsockname()
  114. socks.append(sock)
  115. # I don't *fully* understand why, but it takes *two* un-accepted
  116. # connections to start jamming the socket.
  117. for _ in range(2):
  118. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  119. sock.connect(address)
  120. socks.append(sock)
  121. yield address
  122. finally:
  123. for sock in socks:
  124. sock.close()
  125. class Smoke(avocado.Test):
  126. def setUp(self):
  127. self.proto = NullProtocol()
  128. def test__repr__(self):
  129. self.assertEqual(
  130. repr(self.proto),
  131. "<NullProtocol runstate=IDLE>"
  132. )
  133. def testRunstate(self):
  134. self.assertEqual(
  135. self.proto.runstate,
  136. Runstate.IDLE
  137. )
  138. def testDefaultName(self):
  139. self.assertEqual(
  140. self.proto.name,
  141. None
  142. )
  143. def testLogger(self):
  144. self.assertEqual(
  145. self.proto.logger.name,
  146. 'qemu.aqmp.protocol'
  147. )
  148. def testName(self):
  149. self.proto = NullProtocol('Steve')
  150. self.assertEqual(
  151. self.proto.name,
  152. 'Steve'
  153. )
  154. self.assertEqual(
  155. self.proto.logger.name,
  156. 'qemu.aqmp.protocol.Steve'
  157. )
  158. self.assertEqual(
  159. repr(self.proto),
  160. "<NullProtocol name='Steve' runstate=IDLE>"
  161. )
  162. class TestBase(avocado.Test):
  163. def setUp(self):
  164. self.proto = NullProtocol(type(self).__name__)
  165. self.assertEqual(self.proto.runstate, Runstate.IDLE)
  166. self.runstate_watcher = None
  167. def tearDown(self):
  168. self.assertEqual(self.proto.runstate, Runstate.IDLE)
  169. async def _asyncSetUp(self):
  170. pass
  171. async def _asyncTearDown(self):
  172. if self.runstate_watcher:
  173. await self.runstate_watcher
  174. @staticmethod
  175. def async_test(async_test_method):
  176. """
  177. Decorator; adds SetUp and TearDown to async tests.
  178. """
  179. async def _wrapper(self, *args, **kwargs):
  180. loop = asyncio.get_event_loop()
  181. loop.set_debug(True)
  182. await self._asyncSetUp()
  183. await async_test_method(self, *args, **kwargs)
  184. await self._asyncTearDown()
  185. return _wrapper
  186. # Definitions
  187. # The states we expect a "bad" connect/accept attempt to transition through
  188. BAD_CONNECTION_STATES = (
  189. Runstate.CONNECTING,
  190. Runstate.DISCONNECTING,
  191. Runstate.IDLE,
  192. )
  193. # The states we expect a "good" session to transition through
  194. GOOD_CONNECTION_STATES = (
  195. Runstate.CONNECTING,
  196. Runstate.RUNNING,
  197. Runstate.DISCONNECTING,
  198. Runstate.IDLE,
  199. )
  200. # Helpers
  201. async def _watch_runstates(self, *states):
  202. """
  203. This launches a task alongside (most) tests below to confirm that
  204. the sequence of runstate changes that occur is exactly as
  205. anticipated.
  206. """
  207. async def _watcher():
  208. for state in states:
  209. new_state = await self.proto.runstate_changed()
  210. self.assertEqual(
  211. new_state,
  212. state,
  213. msg=f"Expected state '{state.name}'",
  214. )
  215. self.runstate_watcher = create_task(_watcher())
  216. # Kick the loop and force the task to block on the event.
  217. await asyncio.sleep(0)
  218. class State(TestBase):
  219. @TestBase.async_test
  220. async def testSuperfluousDisconnect(self):
  221. """
  222. Test calling disconnect() while already disconnected.
  223. """
  224. await self._watch_runstates(
  225. Runstate.DISCONNECTING,
  226. Runstate.IDLE,
  227. )
  228. await self.proto.disconnect()
  229. class Connect(TestBase):
  230. """
  231. Tests primarily related to calling Connect().
  232. """
  233. async def _bad_connection(self, family: str):
  234. assert family in ('INET', 'UNIX')
  235. if family == 'INET':
  236. await self.proto.connect(('127.0.0.1', 0))
  237. elif family == 'UNIX':
  238. await self.proto.connect('/dev/null')
  239. async def _hanging_connection(self):
  240. with jammed_socket() as addr:
  241. await self.proto.connect(addr)
  242. async def _bad_connection_test(self, family: str):
  243. await self._watch_runstates(*self.BAD_CONNECTION_STATES)
  244. with self.assertRaises(ConnectError) as context:
  245. await self._bad_connection(family)
  246. self.assertIsInstance(context.exception.exc, OSError)
  247. self.assertEqual(
  248. context.exception.error_message,
  249. "Failed to establish connection"
  250. )
  251. @TestBase.async_test
  252. async def testBadINET(self):
  253. """
  254. Test an immediately rejected call to an IP target.
  255. """
  256. await self._bad_connection_test('INET')
  257. @TestBase.async_test
  258. async def testBadUNIX(self):
  259. """
  260. Test an immediately rejected call to a UNIX socket target.
  261. """
  262. await self._bad_connection_test('UNIX')
  263. @TestBase.async_test
  264. async def testCancellation(self):
  265. """
  266. Test what happens when a connection attempt is aborted.
  267. """
  268. # Note that accept() cannot be cancelled outright, as it isn't a task.
  269. # However, we can wrap it in a task and cancel *that*.
  270. await self._watch_runstates(*self.BAD_CONNECTION_STATES)
  271. task = run_as_task(self._hanging_connection(), allow_cancellation=True)
  272. state = await self.proto.runstate_changed()
  273. self.assertEqual(state, Runstate.CONNECTING)
  274. # This is insider baseball, but the connection attempt has
  275. # yielded *just* before the actual connection attempt, so kick
  276. # the loop to make sure it's truly wedged.
  277. await asyncio.sleep(0)
  278. task.cancel()
  279. await task
  280. @TestBase.async_test
  281. async def testTimeout(self):
  282. """
  283. Test what happens when a connection attempt times out.
  284. """
  285. await self._watch_runstates(*self.BAD_CONNECTION_STATES)
  286. task = run_as_task(self._hanging_connection())
  287. # More insider baseball: to improve the speed of this test while
  288. # guaranteeing that the connection even gets a chance to start,
  289. # verify that the connection hangs *first*, then await the
  290. # result of the task with a nearly-zero timeout.
  291. state = await self.proto.runstate_changed()
  292. self.assertEqual(state, Runstate.CONNECTING)
  293. await asyncio.sleep(0)
  294. with self.assertRaises(asyncio.TimeoutError):
  295. await asyncio.wait_for(task, timeout=0)
  296. @TestBase.async_test
  297. async def testRequire(self):
  298. """
  299. Test what happens when a connection attempt is made while CONNECTING.
  300. """
  301. await self._watch_runstates(*self.BAD_CONNECTION_STATES)
  302. task = run_as_task(self._hanging_connection(), allow_cancellation=True)
  303. state = await self.proto.runstate_changed()
  304. self.assertEqual(state, Runstate.CONNECTING)
  305. with self.assertRaises(StateError) as context:
  306. await self._bad_connection('UNIX')
  307. self.assertEqual(
  308. context.exception.error_message,
  309. "NullProtocol is currently connecting."
  310. )
  311. self.assertEqual(context.exception.state, Runstate.CONNECTING)
  312. self.assertEqual(context.exception.required, Runstate.IDLE)
  313. task.cancel()
  314. await task
  315. @TestBase.async_test
  316. async def testImplicitRunstateInit(self):
  317. """
  318. Test what happens if we do not wait on the runstate event until
  319. AFTER a connection is made, i.e., connect()/accept() themselves
  320. initialize the runstate event. All of the above tests force the
  321. initialization by waiting on the runstate *first*.
  322. """
  323. task = run_as_task(self._hanging_connection(), allow_cancellation=True)
  324. # Kick the loop to coerce the state change
  325. await asyncio.sleep(0)
  326. assert self.proto.runstate == Runstate.CONNECTING
  327. # We already missed the transition to CONNECTING
  328. await self._watch_runstates(Runstate.DISCONNECTING, Runstate.IDLE)
  329. task.cancel()
  330. await task
  331. class Accept(Connect):
  332. """
  333. All of the same tests as Connect, but using the accept() interface.
  334. """
  335. async def _bad_connection(self, family: str):
  336. assert family in ('INET', 'UNIX')
  337. if family == 'INET':
  338. await self.proto.start_server_and_accept(('example.com', 1))
  339. elif family == 'UNIX':
  340. await self.proto.start_server_and_accept('/dev/null')
  341. async def _hanging_connection(self):
  342. with TemporaryDirectory(suffix='.aqmp') as tmpdir:
  343. sock = os.path.join(tmpdir, type(self.proto).__name__ + ".sock")
  344. await self.proto.start_server_and_accept(sock)
  345. class FakeSession(TestBase):
  346. def setUp(self):
  347. super().setUp()
  348. self.proto.fake_session = True
  349. async def _asyncSetUp(self):
  350. await super()._asyncSetUp()
  351. await self._watch_runstates(*self.GOOD_CONNECTION_STATES)
  352. async def _asyncTearDown(self):
  353. await self.proto.disconnect()
  354. await super()._asyncTearDown()
  355. ####
  356. @TestBase.async_test
  357. async def testFakeConnect(self):
  358. """Test the full state lifecycle (via connect) with a no-op session."""
  359. await self.proto.connect('/not/a/real/path')
  360. self.assertEqual(self.proto.runstate, Runstate.RUNNING)
  361. @TestBase.async_test
  362. async def testFakeAccept(self):
  363. """Test the full state lifecycle (via accept) with a no-op session."""
  364. await self.proto.start_server_and_accept('/not/a/real/path')
  365. self.assertEqual(self.proto.runstate, Runstate.RUNNING)
  366. @TestBase.async_test
  367. async def testFakeRecv(self):
  368. """Test receiving a fake/null message."""
  369. await self.proto.start_server_and_accept('/not/a/real/path')
  370. logname = self.proto.logger.name
  371. with self.assertLogs(logname, level='DEBUG') as context:
  372. self.proto.trigger_input.set()
  373. self.proto.trigger_input.clear()
  374. await asyncio.sleep(0) # Kick reader.
  375. self.assertEqual(
  376. context.output,
  377. [f"DEBUG:{logname}:<-- None"],
  378. )
  379. @TestBase.async_test
  380. async def testFakeSend(self):
  381. """Test sending a fake/null message."""
  382. await self.proto.start_server_and_accept('/not/a/real/path')
  383. logname = self.proto.logger.name
  384. with self.assertLogs(logname, level='DEBUG') as context:
  385. # Cheat: Send a Null message to nobody.
  386. await self.proto.send_msg()
  387. # Kick writer; awaiting on a queue.put isn't sufficient to yield.
  388. await asyncio.sleep(0)
  389. self.assertEqual(
  390. context.output,
  391. [f"DEBUG:{logname}:--> None"],
  392. )
  393. async def _prod_session_api(
  394. self,
  395. current_state: Runstate,
  396. error_message: str,
  397. accept: bool = True
  398. ):
  399. with self.assertRaises(StateError) as context:
  400. if accept:
  401. await self.proto.start_server_and_accept('/not/a/real/path')
  402. else:
  403. await self.proto.connect('/not/a/real/path')
  404. self.assertEqual(context.exception.error_message, error_message)
  405. self.assertEqual(context.exception.state, current_state)
  406. self.assertEqual(context.exception.required, Runstate.IDLE)
  407. @TestBase.async_test
  408. async def testAcceptRequireRunning(self):
  409. """Test that accept() cannot be called when Runstate=RUNNING"""
  410. await self.proto.start_server_and_accept('/not/a/real/path')
  411. await self._prod_session_api(
  412. Runstate.RUNNING,
  413. "NullProtocol is already connected and running.",
  414. accept=True,
  415. )
  416. @TestBase.async_test
  417. async def testConnectRequireRunning(self):
  418. """Test that connect() cannot be called when Runstate=RUNNING"""
  419. await self.proto.start_server_and_accept('/not/a/real/path')
  420. await self._prod_session_api(
  421. Runstate.RUNNING,
  422. "NullProtocol is already connected and running.",
  423. accept=False,
  424. )
  425. @TestBase.async_test
  426. async def testAcceptRequireDisconnecting(self):
  427. """Test that accept() cannot be called when Runstate=DISCONNECTING"""
  428. await self.proto.start_server_and_accept('/not/a/real/path')
  429. # Cheat: force a disconnect.
  430. await self.proto.simulate_disconnect()
  431. await self._prod_session_api(
  432. Runstate.DISCONNECTING,
  433. ("NullProtocol is disconnecting."
  434. " Call disconnect() to return to IDLE state."),
  435. accept=True,
  436. )
  437. @TestBase.async_test
  438. async def testConnectRequireDisconnecting(self):
  439. """Test that connect() cannot be called when Runstate=DISCONNECTING"""
  440. await self.proto.start_server_and_accept('/not/a/real/path')
  441. # Cheat: force a disconnect.
  442. await self.proto.simulate_disconnect()
  443. await self._prod_session_api(
  444. Runstate.DISCONNECTING,
  445. ("NullProtocol is disconnecting."
  446. " Call disconnect() to return to IDLE state."),
  447. accept=False,
  448. )
  449. class SimpleSession(TestBase):
  450. def setUp(self):
  451. super().setUp()
  452. self.server = LineProtocol(type(self).__name__ + '-server')
  453. async def _asyncSetUp(self):
  454. await super()._asyncSetUp()
  455. await self._watch_runstates(*self.GOOD_CONNECTION_STATES)
  456. async def _asyncTearDown(self):
  457. await self.proto.disconnect()
  458. try:
  459. await self.server.disconnect()
  460. except EOFError:
  461. pass
  462. await super()._asyncTearDown()
  463. @TestBase.async_test
  464. async def testSmoke(self):
  465. with TemporaryDirectory(suffix='.aqmp') as tmpdir:
  466. sock = os.path.join(tmpdir, type(self.proto).__name__ + ".sock")
  467. server_task = create_task(self.server.start_server_and_accept(sock))
  468. # give the server a chance to start listening [...]
  469. await asyncio.sleep(0)
  470. await self.proto.connect(sock)