Debian Codegraph @

test/pytest/test_transport.py

raw
1 #
2 # Copyright (C) 2022 Red Hat, Inc.
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5
6 import asyncio
7 import contextlib
8 import errno
9 import os
10 import signal
11 import subprocess
12 import unittest.mock
13 from typing import Any, List, Optional, Tuple
14
15 import pytest
16
17 import cockpit.transports
18
19
20 class Protocol(cockpit.transports.SubprocessProtocol):
21 transport: Optional[asyncio.Transport] = None
22 paused: bool = False
23 sent: int = 0
24 received: int = 0
25 exited: bool = False
26 close_on_eof: bool = True
27 eof: bool = False
28 exc: Optional[Exception] = None
29 output: Optional[List[bytes]] = None
30
31 def connection_made(self, transport: asyncio.BaseTransport) -> None:
32 assert isinstance(transport, asyncio.Transport)
33 self.transport = transport
34
35 def connection_lost(self, exc: Optional[Exception] = None) -> None:
36 self.transport = None
37 self.exc = exc
38
39 def data_received(self, data: bytes) -> None:
40 if self.output is not None:
41 self.output.append(data)
42 self.received += len(data)
43
44 def eof_received(self) -> bool:
45 self.eof = True
46 return not self.close_on_eof
47
48 def pause_writing(self) -> None:
49 self.paused = True
50
51 def write_until_backlogged(self) -> None:
52 while not self.paused:
53 self.write(b'a' * 4096)
54
55 def write(self, data: bytes) -> None:
56 assert self.transport is not None
57 self.transport.write(data)
58 self.sent += len(data)
59
60 def write_a_lot(self) -> None:
61 assert self.transport is not None
62 self.write_until_backlogged()
63 assert self.transport.get_write_buffer_size() != 0
64 for _ in range(20):
65 self.write(b'b' * 1024 * 1024)
66 assert self.transport.get_write_buffer_size() > 20 * 1024 * 1024
67
68 def process_exited(self) -> None:
69 self.exited = True
70
71 def get_output(self) -> bytes:
72 assert self.output is not None
73 return b''.join(self.output)
74
75 async def eof_and_exited_with_code(self, returncode) -> None:
76 self.close_on_eof = False # otherwise we won't get process_exited()
77 transport = self.transport
78 assert isinstance(transport, cockpit.transports.SubprocessTransport)
79 while not self.exited or not self.eof:
80 await asyncio.sleep(0.1)
81 assert transport.get_returncode() == returncode
82
83
84 class TestSpooler:
85 @pytest.mark.asyncio
86 async def test_bad_fd(self) -> None:
87 # Make sure failing to construct succeeds without further failures
88 loop = asyncio.get_running_loop()
89 with pytest.raises(OSError) as raises:
90 cockpit.transports.Spooler(loop, -1)
91 assert raises.value.errno == errno.EBADF
92
93 def create_spooler(self, to_write: bytes = b'') -> cockpit.transports.Spooler:
94 loop = asyncio.get_running_loop()
95 reader, writer = os.pipe()
96 try:
97 spooler = cockpit.transports.Spooler(loop, reader)
98 finally:
99 os.close(reader)
100 try:
101 os.write(writer, to_write)
102 finally:
103 os.close(writer)
104 return spooler
105
106 @pytest.mark.asyncio
107 async def test_poll_eof(self) -> None:
108 spooler = self.create_spooler()
109 while spooler._fd != -1:
110 await asyncio.sleep(0.1)
111 assert spooler.get() == b''
112
113 @pytest.mark.asyncio
114 async def test_nopoll_eof(self) -> None:
115 spooler = self.create_spooler()
116 assert spooler.get() == b''
117 assert spooler._fd == -1
118
119 @pytest.mark.asyncio
120 async def test_poll_small(self) -> None:
121 spooler = self.create_spooler(b'abcd')
122 while spooler._fd != -1:
123 await asyncio.sleep(0.1)
124 assert spooler.get() == b'abcd'
125
126 @pytest.mark.asyncio
127 async def test_nopoll_small(self) -> None:
128 spooler = self.create_spooler(b'abcd')
129 assert spooler.get() == b'abcd'
130 assert spooler._fd == -1
131
132 @pytest.mark.asyncio
133 async def test_big(self) -> None:
134 loop = asyncio.get_running_loop()
135 reader, writer = os.pipe()
136 try:
137 spooler = cockpit.transports.Spooler(loop, reader)
138 finally:
139 os.close(reader)
140
141 try:
142 os.set_blocking(writer, False)
143 written = 0
144 blob = b'a' * 64 * 1024 # NB: pipe buffer is 64k
145 while written < 1024 * 1024:
146 # Note: we should never get BlockingIOError here since we always
147 # give the reader a chance to drain the pipe.
148 written += os.write(writer, blob)
149 while len(spooler.get()) < written:
150 await asyncio.sleep(0.01)
151
152 assert spooler._fd != -1
153 finally:
154 os.close(writer)
155
156 await asyncio.sleep(0.1)
157 assert spooler._fd == -1
158
159 assert len(spooler.get()) == written
160
161
162 class TestEpollLimitations:
163 # https://github.com/python/cpython/issues/73903
164 #
165 # There are some types of files that epoll doesn't work with, returning
166 # EPERM. We might be in a situation where we receive one of those on
167 # stdin/stdout for AsyncioTransport, so we'd theoretically like to support
168 # them.
169 async def spool_file(self, filename: str) -> None:
170 loop = asyncio.get_running_loop()
171 with open(filename) as fp:
172 spooler = cockpit.transports.Spooler(loop, fp.fileno())
173 while spooler._fd != -1:
174 await asyncio.sleep(0.1)
175
176 @pytest.mark.xfail
177 @pytest.mark.asyncio
178 async def test_read_file(self) -> None:
179 await self.spool_file(__file__)
180
181 @pytest.mark.xfail
182 @pytest.mark.asyncio
183 async def test_dev_null(self) -> None:
184 await self.spool_file('/dev/null')
185
186
187 class TestStdio:
188 @contextlib.contextmanager
189 def create_terminal(self):
190 ours, theirs = os.openpty()
191 stdin = os.dup(theirs)
192 stdout = os.dup(theirs)
193 os.close(theirs)
194 loop = asyncio.get_running_loop()
195 protocol = Protocol()
196 try:
197 yield ours, protocol, cockpit.transports.StdioTransport(loop, protocol, stdin=stdin, stdout=stdout)
198 finally:
199 os.close(stdin)
200 os.close(stdout)
201
202 @pytest.mark.asyncio
203 async def test_terminal_write_eof(self):
204 # Make sure write_eof() fails
205 with self.create_terminal() as (ours, _protocol, transport):
206 assert not transport.can_write_eof()
207 with pytest.raises(RuntimeError):
208 transport.write_eof()
209 os.close(ours)
210
211 @pytest.mark.asyncio
212 async def test_terminal_disconnect(self):
213 # Make sure disconnecting the session shows up as an EOF
214 with self.create_terminal() as (ours, protocol, _transport):
215 os.close(ours)
216 while not protocol.eof:
217 await asyncio.sleep(0.1)
218
219
220 class TestSubprocessTransport:
221 def subprocess(self, args, **kwargs: Any) -> Tuple[Protocol, cockpit.transports.SubprocessTransport]:
222 loop = asyncio.get_running_loop()
223 protocol = Protocol()
224 transport = cockpit.transports.SubprocessTransport(loop, protocol, args, **kwargs)
225 assert transport._protocol == protocol
226 assert protocol.transport == transport
227 return protocol, transport
228
229 @pytest.mark.asyncio
230 async def test_true(self) -> None:
231 protocol, transport = self.subprocess(['true'])
232 await protocol.eof_and_exited_with_code(0)
233 assert transport.get_stderr() == ''
234
235 @pytest.mark.asyncio
236 async def test_cat(self) -> None:
237 protocol, transport = self.subprocess(['cat'])
238 protocol.close_on_eof = False
239 protocol.write_a_lot()
240 assert transport.can_write_eof()
241 transport.write_eof()
242 await protocol.eof_and_exited_with_code(0)
243 assert protocol.transport is not None # should not have automatically closed
244 assert transport.get_returncode() == 0
245 assert protocol.sent == protocol.received
246 transport.close()
247 # make sure the connection_lost handler isn't called immediately
248 assert protocol.transport is not None
249 # ...but "soon" (in the very next mainloop iteration)
250 await asyncio.sleep(0.01)
251 assert protocol.transport is None
252
253 @pytest.mark.asyncio
254 async def test_send_signal(self) -> None:
255 protocol, transport = self.subprocess(['cat'])
256 transport.send_signal(signal.SIGTERM)
257 await protocol.eof_and_exited_with_code(-signal.SIGTERM)
258
259 @pytest.mark.asyncio
260 async def test_pid(self) -> None:
261 protocol, transport = self.subprocess(['sh', '-c', 'echo $$'])
262 protocol.output = []
263 await protocol.eof_and_exited_with_code(0)
264 assert int(protocol.get_output()) == transport.get_pid()
265
266 @pytest.mark.asyncio
267 async def test_terminate(self) -> None:
268 protocol, transport = self.subprocess(['cat'])
269 transport.kill()
270 await protocol.eof_and_exited_with_code(-signal.SIGKILL)
271
272 protocol, transport = self.subprocess(['cat'])
273 transport.terminate()
274 await protocol.eof_and_exited_with_code(-signal.SIGTERM)
275
276 @pytest.mark.asyncio
277 async def test_stderr(self) -> None:
278 loop = asyncio.get_running_loop()
279 protocol = Protocol()
280 transport = cockpit.transports.SubprocessTransport(loop, protocol, ['cat', '/nonexistent'],
281 stderr=subprocess.PIPE)
282 await protocol.eof_and_exited_with_code(1)
283 assert protocol.received == protocol.sent == 0
284 # Unless we reset it, we should get the same result repeatedly
285 assert '/nonexistent' in transport.get_stderr()
286 assert '/nonexistent' in transport.get_stderr()
287 assert '/nonexistent' in transport.get_stderr(reset=True)
288 # After we reset, it should be the empty string
289 assert transport.get_stderr() == ''
290 assert transport.get_stderr(reset=True) == ''
291
292 @pytest.mark.asyncio
293 async def test_pidfd_ENOSYS(self, monkeypatch: pytest.MonkeyPatch) -> None:
294 # this test disables pidfd support in order to force the fallback path
295 monkeypatch.setattr(os, 'pidfd_open', unittest.mock.Mock(side_effect=OSError), raising=False)
296 protocol, _transport = self.subprocess(['true'])
297 await protocol.eof_and_exited_with_code(0)
298
299 @pytest.mark.asyncio
300 async def test_pidfd_ENOSYS_nonzero_exit(self, monkeypatch: pytest.MonkeyPatch) -> None:
301 # test that non-zero exit codes are correctly reported via the threaded fallback path
302 monkeypatch.setattr(os, 'pidfd_open', unittest.mock.Mock(side_effect=OSError), raising=False)
303 protocol, _transport = self.subprocess(['false'])
304 await protocol.eof_and_exited_with_code(1)
305
306 @pytest.mark.asyncio
307 async def test_pidfd_ENOSYS_exit_code(self, monkeypatch: pytest.MonkeyPatch) -> None:
308 # test that specific exit codes are correctly reported via the threaded fallback path
309 monkeypatch.setattr(os, 'pidfd_open', unittest.mock.Mock(side_effect=OSError), raising=False)
310 protocol, _transport = self.subprocess(['sh', '-c', 'exit 42'])
311 await protocol.eof_and_exited_with_code(42)
312
313 @pytest.mark.asyncio
314 async def test_pidfd_ENOSYS_signal(self, monkeypatch: pytest.MonkeyPatch) -> None:
315 # test that signal termination is correctly reported via the threaded fallback path
316 monkeypatch.setattr(os, 'pidfd_open', unittest.mock.Mock(side_effect=OSError), raising=False)
317 protocol, transport = self.subprocess(['cat'])
318 transport.send_signal(signal.SIGTERM)
319 await protocol.eof_and_exited_with_code(-signal.SIGTERM)
320
321 @pytest.mark.asyncio
322 async def test_pidfd_ENOSYS_kill(self, monkeypatch: pytest.MonkeyPatch) -> None:
323 # test that SIGKILL is correctly reported via the threaded fallback path
324 monkeypatch.setattr(os, 'pidfd_open', unittest.mock.Mock(side_effect=OSError), raising=False)
325 protocol, transport = self.subprocess(['cat'])
326 transport.kill()
327 await protocol.eof_and_exited_with_code(-signal.SIGKILL)
328
329 @pytest.mark.asyncio
330 async def test_pidfd_ENOSYS_concurrent(self, monkeypatch: pytest.MonkeyPatch) -> None:
331 # test multiple concurrent subprocesses with different exit scenarios
332 # using the threaded fallback path, to ensure exit statuses don't get mixed up
333 monkeypatch.setattr(os, 'pidfd_open', unittest.mock.Mock(side_effect=OSError), raising=False)
334
335 # start processes that block on stdin - we control when they exit
336 proto_0, transport_0 = self.subprocess(['sh', '-c', 'read a; exit 0'])
337 proto_1, transport_1 = self.subprocess(['sh', '-c', 'read a; exit 1'])
338 proto_42, transport_42 = self.subprocess(['sh', '-c', 'read a; exit 42'])
339 proto_term, transport_term = self.subprocess(['sh', '-c', 'read a; exit 99'])
340 proto_kill, transport_kill = self.subprocess(['sh', '-c', 'read a; exit 99'])
341
342 # create tasks for each process
343 task_0 = asyncio.create_task(proto_0.eof_and_exited_with_code(0))
344 task_1 = asyncio.create_task(proto_1.eof_and_exited_with_code(1))
345 task_42 = asyncio.create_task(proto_42.eof_and_exited_with_code(42))
346 task_term = asyncio.create_task(proto_term.eof_and_exited_with_code(-signal.SIGTERM))
347 task_kill = asyncio.create_task(proto_kill.eof_and_exited_with_code(-signal.SIGKILL))
348 pending = {task_0, task_1, task_42, task_term, task_kill}
349
350 # exit them one by one in a specific order and verify each time
351 transport_kill.kill()
352 done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
353 assert done == {task_kill}
354 task_kill.result()
355
356 transport_term.send_signal(signal.SIGTERM)
357 done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
358 assert done == {task_term}
359 task_term.result()
360
361 transport_42.write_eof()
362 done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
363 assert done == {task_42}
364 task_42.result()
365
366 transport_1.write_eof()
367 done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
368 assert done == {task_1}
369 task_1.result()
370
371 transport_0.write_eof()
372 done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
373 assert done == {task_0}
374 task_0.result()
375
376 assert not pending
377
378 @pytest.mark.asyncio
379 async def test_true_pty(self) -> None:
380 loop = asyncio.get_running_loop()
381 protocol = Protocol()
382 transport = cockpit.transports.SubprocessTransport(loop, protocol, ['true'], pty=True)
383 assert not transport.can_write_eof()
384 await protocol.eof_and_exited_with_code(0)
385 assert protocol.received == protocol.sent == 0
386
387 @pytest.mark.asyncio
388 async def test_broken_pipe(self) -> None:
389 loop = asyncio.get_running_loop()
390 protocol = Protocol()
391 transport = cockpit.transports.SubprocessTransport(loop, protocol, ['true'])
392 protocol.close_on_eof = False
393 while not protocol.exited:
394 await asyncio.sleep(0.1)
395
396 assert protocol.transport is transport # should not close on EOF
397
398 # Now let's write to the stdin with the other side closed.
399 # This should be enough to immediately disconnect us (EPIPE)
400 protocol.write(b'abc')
401 # make sure the connection_lost handler isn't called immediately
402 assert protocol.transport is not None
403 # ...but "soon" (in the very next mainloop iteration)
404 await asyncio.sleep(0.01)
405 assert protocol.transport is None
406 assert isinstance(protocol.exc, BrokenPipeError)
407
408 @pytest.mark.asyncio
409 async def test_broken_pipe_backlog(self) -> None:
410 loop = asyncio.get_running_loop()
411 protocol = Protocol()
412 transport = cockpit.transports.SubprocessTransport(loop, protocol, ['cat'])
413 protocol.close_on_eof = False
414
415 # Since we're not reading, cat's stdout will back up and it will be
416 # forced to stop reading at some point. We'll still have a rather full
417 # write buffer.
418 protocol.write_a_lot()
419
420 # This will result in the stdin closing. Our next attempt to write to
421 # the buffer should end badly (EPIPE).
422 transport.kill()
423
424 while protocol.transport:
425 await asyncio.sleep(0.1)
426
427 assert protocol.transport is None
428 assert isinstance(protocol.exc, BrokenPipeError)
429
430 @pytest.mark.asyncio
431 async def test_window_size(self) -> None:
432 protocol, transport = self.subprocess(['bash', '-ic',
433 """
434 while true; do
435 sleep 0.1
436 echo ${LINES}x${COLUMNS}
437 done
438 """],
439 pty=True,
440 window=cockpit.transports.WindowSize({'rows': 22, 'cols': 33}))
441 protocol.output = []
442 while b'22x33\r\n' not in protocol.get_output():
443 await asyncio.sleep(0.1)
444
445 transport.set_window_size(cockpit.transports.WindowSize({'rows': 44, 'cols': 55}))
446 while b'44x55\r\n' not in protocol.get_output():
447 await asyncio.sleep(0.1)
448
449 transport.close()
450
451 @pytest.mark.asyncio
452 async def test_env(self) -> None:
453 protocol, transport = self.subprocess(['bash', '-ic', 'echo $HOME'],
454 pty=True,
455 env={'HOME': '/test'})
456 protocol.output = []
457 while b'/test\r\n' not in protocol.get_output():
458 await asyncio.sleep(0.1)
459
460 transport.close()
461
462 @pytest.mark.asyncio
463 async def test_simple_close(self) -> None:
464 protocol, transport = self.subprocess(['cat'])
465 protocol.output = []
466
467 protocol.write(b'abcd')
468 assert protocol.transport
469 assert protocol.transport.get_write_buffer_size() == 0
470 protocol.transport.close()
471 # make sure the connection_lost handler isn't called immediately
472 assert protocol.transport is not None
473 # ...but "soon" (in the very next mainloop iteration)
474 await asyncio.sleep(0.01)
475 assert protocol.transport is None
476 # we have another ref on the transport
477 transport.close() # should be idempotent
478
479 @pytest.mark.asyncio
480 async def test_flow_control(self) -> None:
481 protocol, transport = self.subprocess(['cat'])
482 protocol.output = []
483
484 protocol.write(b'abcd')
485 assert protocol.transport is not None
486 transport.pause_reading()
487 await asyncio.sleep(0.1)
488 transport.resume_reading()
489 while protocol.received < 4:
490 await asyncio.sleep(0.1)
491 assert protocol.transport is not None
492 transport.write_eof()
493 protocol.close_on_eof = False
494 while not protocol.eof:
495 await asyncio.sleep(0.1)
496 assert not transport.is_reading()
497 transport.pause_reading() # no-op
498 assert not transport.is_reading()
499 transport.resume_reading() # no-op
500 assert not transport.is_reading()
501
502 @pytest.mark.asyncio
503 async def test_write_backlog_eof(self) -> None:
504 protocol, transport = self.subprocess(['cat'])
505 protocol.output = []
506 protocol.write_a_lot()
507
508 assert transport.can_write_eof()
509 transport.write_eof()
510 assert not transport.is_closing()
511 while protocol.transport is not None:
512 await asyncio.sleep(0.1)
513 assert protocol.transport is None
514
515 @pytest.mark.asyncio
516 async def test_write_backlog_close(self) -> None:
517 protocol, transport = self.subprocess(['cat'])
518 protocol.output = []
519 protocol.write_a_lot()
520
521 assert transport
522 transport.close()
523 assert transport.is_closing()
524 # FIXME: closing the channel should kill the process, like asyncio's SubprocessTransport
525 # See https://github.com/cockpit-project/cockpit/pull/18340
526 transport.kill()
527 while protocol.transport is not None:
528 await asyncio.sleep(0.1)
529 assert protocol.transport is None
530
531 @pytest.mark.asyncio
532 async def test_write_backlog_eof_and_close(self) -> None:
533 protocol, transport = self.subprocess(['cat'])
534 protocol.output = []
535 protocol.write_a_lot()
536
537 assert transport
538 transport.write_eof()
539 transport.close()
540 assert protocol.transport
541 assert protocol.transport.is_closing()
542 # FIXME: closing the channel should kill the process, like asyncio's SubprocessTransport
543 # See https://github.com/cockpit-project/cockpit/pull/18340
544 transport.kill()
545 while protocol.transport is not None:
546 await asyncio.sleep(0.1)
547 assert protocol.transport is None