Debian Codegraph @

crt/s2n/tests/integrationv2/processes.py

raw symbols SCIP
1 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 # SPDX-License-Identifier: Apache-2.0
3 import os
4 import select
5 import selectors
6 import subprocess
7 import threading
8
9 from common import Results, TimeoutException
10 from time import monotonic as _time
11
12
13 _PopenSelector = selectors.PollSelector
14 _PIPE_BUF = getattr(select, "PIPE_BUF", 512)
15 _DEBUG_LEN = 200
16
17
18 class _processCommunicator(object):
19 """
20 This class allows greater control over stdin than using Popen.communicate().
21 Popen.communicate() closes stdin as soon as data is written. This causes
22 TLS clients (OpenSSL derivatives) to shut down before the handshake is complete.
23
24 To prevent a premature shutdown, we need to wait until the handshake is complete
25 before writing to stdin. To accomplish this we `poll` stdout for a send
26 marker. Once that marker is found, we can write input data to stdin. The
27 benefit of using `poll` and `os.read` is that we get non-blocking IO. Our timeouts
28 are much more reliable, and we don't risk deadlocking on a readline() call which
29 will never complete.
30
31 Another method is to read stdout line by line. This removes a lot of code that
32 registers and unregisters file descriptors with a selector. It would make reading
33 and writing sequential (as opposed to event based), which can be easier to read
34 and maintain. The downsides with this method exist in the current integration test
35 framework. We rely on sleeps and waits, and still hit hard to debug deadlocks from
36 time to time.
37 """
38
39 def __init__(self, proc, name):
40 self.proc = proc
41 self.wait_for_marker = None
42 self.name = name
43
44 # If the process times out, communicate() is called once more to pick
45 # up any data remaining in stdout/stderr. This flags lets us know if
46 # we need to do initial setup on the file descriptors, or if it was done
47 # during the initial call.
48 self._communication_started = False
49
50 def wait_for(self, wait_for_marker, timeout=None):
51 """
52 Wait for a specific marker in stdout.
53 If the marker is not seen, a timeout will be raised.
54 """
55 self.wait_for_marker = wait_for_marker
56 stdout = None
57 stderr = None
58
59 try:
60 stdout, stderr = self._communicate(None, timeout=timeout)
61 finally:
62 self._communication_started = True
63
64 return (stdout, stderr)
65
66 def communicate(
67 self,
68 input_data=None,
69 send_marker_list=None,
70 close_marker=None,
71 kill_marker=None,
72 send_with_newline=False,
73 timeout=None,
74 ):
75 """
76 Communicates with the managed process. If send_marker_list is set, input_data will not be sent
77 until the marker is seen.
78
79 This method acts very similar to the Popen.communicate method. The only difference is the
80 send_marker_list and close_marker.
81 """
82 self.wait_for_marker = None
83 stdout = None
84 stderr = None
85
86 try:
87 stdout, stderr = self._communicate(
88 input_data,
89 send_marker_list,
90 close_marker,
91 kill_marker,
92 send_with_newline,
93 timeout,
94 )
95 finally:
96 self._communication_started = True
97
98 return (stdout, stderr)
99
100 # Helper function to print out debugging statements
101 def get_fd_name(self, proc, fileobj):
102 if fileobj == proc.stdout:
103 return "stdout"
104 elif fileobj == proc.stderr:
105 return "stderr"
106 elif fileobj == proc.stdin:
107 return "stdin"
108 return "unknown fd"
109
110 def _communicate(
111 self,
112 input_data=None,
113 send_marker_list=None,
114 close_marker=None,
115 kill_marker=None,
116 send_with_newline=False,
117 timeout=None,
118 ):
119 print(
120 f"{self.name}: Handling process IO: \n"
121 f" wait_for_marker: {self.wait_for_marker} \n"
122 f" send_markers: {send_marker_list} \n"
123 f" close_marker: {close_marker} \n"
124 f" kill_marker: {kill_marker}"
125 )
126
127 """
128 This method will read and write data to a subprocess in a non-blocking manner.
129 The code is heavily based on Popen.communicate. There are a couple differences:
130
131 * STDIN is not registered for events until the read_to_send marker is found
132 * STDIN is only closed after all registered events have been processed (including
133 pending stdout/stderr events, allowing more data to be stored).
134 """
135 if input_data is not None and self.proc.stdin:
136 # Flush stdio buffer. This might block, if the user has
137 # been writing to .stdin in an uncontrolled fashion.
138 try:
139 self.proc.stdin.flush()
140 except BrokenPipeError:
141 pass # communicate() must ignore BrokenPipeError.
142
143 # The process' stdout and stderr are stored in a map, with two variable
144 # pointing to the file objects. This allows us to include stdout/stderr
145 # data in a timeout exception.
146 if not self._communication_started:
147 self._fileobj2output = {}
148 if self.proc.stdout:
149 self._fileobj2output[self.proc.stdout] = []
150 if self.proc.stderr:
151 self._fileobj2output[self.proc.stderr] = []
152
153 stdout = self._fileobj2output[self.proc.stdout]
154 stderr = self._fileobj2output[self.proc.stderr]
155
156 input_data_len = 0
157 input_data_offset = 0
158 input_data_sent = False
159 send_marker = None
160 if send_marker_list:
161 send_marker = send_marker_list.pop(0)
162
163 # Keeping track of the original timeout value, and the expected end
164 # time of the operation allow us to timeout while reads/writes are
165 # still pending. It also allows us to only wait for the remainder of
166 # the timeout after reads/writes have completed.
167 orig_timeout = timeout
168 if timeout is not None:
169 endtime = _time() + timeout
170 else:
171 endtime = None
172
173 with _PopenSelector() as selector:
174 if self.proc.stdout and not self.proc.stdout.closed:
175 selector.register(self.proc.stdout, selectors.EVENT_READ)
176 if self.proc.stderr and not self.proc.stderr.closed:
177 selector.register(self.proc.stderr, selectors.EVENT_READ)
178
179 while selector.get_map():
180 timeout = self._remaining_time(endtime)
181 if timeout is not None and timeout < 0:
182 self._check_timeout(
183 endtime, orig_timeout, stdout, stderr, skip_check_and_raise=True
184 )
185 raise RuntimeError( # Impossible :)
186 "_check_timeout(..., skip_check_and_raise=True) "
187 "failed to raise TimeoutExpired."
188 )
189
190 ready = selector.select(timeout)
191 self._check_timeout(endtime, orig_timeout, stdout, stderr)
192
193 # (Key, events) tuple represents a single I/O operation
194 for key, num_events in ready:
195 # STDIN is only registered to receive events after the send_marker is found.
196 if key.fileobj is self.proc.stdin:
197 print(f"{self.name}: stdin available")
198 chunk = input_view[ # noqa: F821
199 input_data_offset : input_data_offset + _PIPE_BUF
200 ]
201 try:
202 input_data_offset += os.write(key.fd, chunk)
203 print(f"{self.name}: sent")
204 except BrokenPipeError:
205 print(f"{self.name}: Unregistering (stdin) BrokenPipeError")
206 selector.unregister(self.proc.stdin)
207 else:
208 if input_data_offset >= input_data_len:
209 print(
210 f"{self.name}: Unregistering (stdin) Input_data_offset >= input_data_len"
211 )
212 selector.unregister(self.proc.stdin)
213 input_data_sent = True
214 input_data_offset = 0
215 if send_marker_list:
216 send_marker = send_marker_list.pop(0)
217 print(
218 f"{self.name}: next send_marker is {send_marker}"
219 )
220 elif key.fileobj in (self.proc.stdout, self.proc.stderr):
221 fd_name = self.get_fd_name(self.proc, key.fileobj)
222 print(f"{self.name}: {fd_name} available")
223
224 # 32 KB (32 × 1024 = 32,768 bytes), read 32KB from the file descriptor
225 data = os.read(key.fd, 32768)
226 if not data:
227 selector.unregister(key.fileobj)
228 print(f"{self.name}: Unregistering: {fd_name} No Data")
229
230 data_str = str(data)
231
232 # Prepends n - 1 bytes of previously-seen stdout to the chunk we'll be searching
233 # through, where n is the size of the send_marker we're currently looking for.
234 # This ensures a marker doesn't get split between chunks and we miss it.
235 if self._fileobj2output[key.fileobj] and send_marker:
236 stored_stdout_list = self._fileobj2output[key.fileobj]
237 send_marker_len = len(send_marker) - 1
238 if len(stored_stdout_list) > 0:
239 data_str = str(
240 stored_stdout_list[-1][-send_marker_len:] + data
241 )
242
243 data_debug = data_str[:_DEBUG_LEN]
244 if len(data_str) > _DEBUG_LEN:
245 data_debug += (
246 f" ...({len(data_str) - _DEBUG_LEN} more bytes)"
247 )
248
249 # fileobj2output[key.fileobj] is a list of data chunks
250 # that get joined later
251 self._fileobj2output[key.fileobj].append(data)
252
253 # If we are looking for, and find, the ready-to-send marker, then
254 # register STDIN to receive events. If there is no data to send,
255 # just mark input_send as true so we can close out STDIN.
256 if send_marker:
257 print(
258 f"{self.name}: looking for send_marker {send_marker} in {data_debug}"
259 )
260 if send_marker is not None and send_marker in data_str:
261 print(f"{self.name}: found {send_marker}")
262 send_marker = None
263 if self.proc.stdin and input_data:
264 selector.register(
265 self.proc.stdin, selectors.EVENT_WRITE
266 )
267 message = input_data.pop(0)
268 if send_with_newline:
269 message += b"\n"
270 # Data destined for stdin is stored in a memoryview
271 input_view = memoryview(message) # noqa: F841
272 input_data_len = len(message)
273 input_data_sent = False
274 print(f"{self.name}: will send {message}")
275 else:
276 input_data_sent = True
277 print(f"{self.name}: will send nothing")
278
279 if self.wait_for_marker:
280 print(
281 f"{self.name}: looking for wait_for_marker {self.wait_for_marker} in {data_debug}"
282 )
283 if (
284 self.wait_for_marker is not None
285 and self.wait_for_marker in data_str
286 ):
287 print(
288 f"{self.name}: Unregistering (stdout + stderr), found wait_for_marker"
289 )
290 selector.unregister(self.proc.stdout)
291 selector.unregister(self.proc.stderr)
292 return None, None
293
294 if kill_marker:
295 print(
296 f"{self.name}: looking for kill_marker {kill_marker} in {data}"
297 )
298 if kill_marker is not None and kill_marker in data:
299 print(
300 f"{self.name}: Unregistering (stdout + stderr), found kill_marker"
301 )
302 selector.unregister(self.proc.stdout)
303 selector.unregister(self.proc.stderr)
304 self.proc.kill()
305
306 if self.proc.stdin and input_data_sent and not input_data:
307 print(f"{self.name}: finished sending")
308 if close_marker:
309 print(
310 f"{self.name}: looking for close_marker {close_marker} in {data_debug}"
311 )
312 if close_marker is None or (
313 close_marker and close_marker in data_str
314 ):
315 print(f"{self.name}: Found close marker: closing stdin")
316 input_data_sent = None
317 self.proc.stdin.close()
318
319 self.proc.wait(timeout=self._remaining_time(endtime))
320
321 # All data exchanged. Translate lists into strings.
322 if stdout is not None:
323 stdout = b"".join(stdout)
324 if stderr is not None:
325 stderr = b"".join(stderr)
326
327 return (stdout, stderr)
328
329 def _remaining_time(self, endtime):
330 """Convenience for _communicate when computing timeouts."""
331 if endtime is None:
332 return None
333 else:
334 return endtime - _time()
335
336 def _check_timeout(
337 self, endtime, orig_timeout, stdout_seq, stderr_seq, skip_check_and_raise=False
338 ):
339 """
340 Convenience for checking if a timeout has expired.
341
342 NOTE: This method is included here to prevent our custom _communicate method
343 from relying on a particular version of Python.
344 """
345 if endtime is None:
346 return
347 if skip_check_and_raise or _time() > endtime:
348 raise subprocess.TimeoutExpired(
349 self.proc.args,
350 orig_timeout,
351 output=b"".join(stdout_seq) if stdout_seq else None,
352 stderr=b"".join(stderr_seq) if stderr_seq else None,
353 )
354
355
356 class ManagedProcess(threading.Thread):
357 """
358 A ManagedProcess is a thread that monitors a subprocess.
359 This class provides a single place to control process timeouts and cleanup.
360
361 The stdin/stdout/stderr and exist code a monitored and results
362 are made available to the caller.
363 """
364
365 def __init__(
366 self,
367 cmd_line,
368 provider_set_ready_condition,
369 name,
370 wait_for_marker=None,
371 send_marker_list=None,
372 close_marker=None,
373 timeout=5,
374 data_source=None,
375 env_overrides=dict(),
376 expect_stderr=False,
377 kill_marker=None,
378 send_with_newline=False,
379 ):
380 threading.Thread.__init__(self)
381
382 proc_env = os.environ.copy()
383
384 for key in env_overrides:
385 proc_env[key] = env_overrides[key]
386
387 self.proc_env = proc_env
388
389 # Command line to execute in the subprocess
390 self.cmd_line = list(map(str, cmd_line))
391
392 self.name = name
393
394 # Total time to wait until killing the subprocess
395 self.timeout = timeout
396
397 # Condition variable indicating when results are ready to be collected
398 self.results_condition = threading.Condition()
399 self.results = None
400
401 # Condition variable indicating when this subprocess has been launched successfully
402 self.ready_condition = threading.Condition()
403 self.process_ready = False
404 self.provider_set_ready_condition = provider_set_ready_condition
405
406 # Indicates the process has completed some initial setup and is ready for testing
407 self.ready_to_test = wait_for_marker
408
409 self.close_marker = close_marker
410 self.data_source = data_source
411 self.send_marker_list = send_marker_list
412 self.expect_stderr = expect_stderr
413 self.kill_marker = kill_marker
414 self.send_with_newline = send_with_newline
415
416 if data_source is not None:
417 if type(data_source) is not list:
418 self.data_source = [data_source]
419
420 if send_marker_list is not None:
421 if type(send_marker_list) is not list:
422 self.send_marker_list = [send_marker_list]
423
424 def run(self):
425 with self.results_condition:
426 try:
427 proc = subprocess.Popen(
428 self.cmd_line,
429 env=self.proc_env,
430 stdin=subprocess.PIPE,
431 stdout=subprocess.PIPE,
432 stderr=subprocess.PIPE,
433 close_fds=True,
434 )
435 self.proc = proc
436 except Exception as ex:
437 self.results = Results(None, None, None, ex, self.expect_stderr)
438 raise ex
439
440 communicator = _processCommunicator(proc, self.name)
441
442 if self.ready_to_test is not None:
443 # Some processes won't be ready until they have emitted some string in stdout.
444 communicator.wait_for(self.ready_to_test, timeout=self.timeout)
445
446 # Let any threads waiting on process launch proceed
447 self.provider_set_ready_condition()
448
449 proc_results = None
450 try:
451 proc_results = communicator.communicate(
452 input_data=self.data_source,
453 send_marker_list=self.send_marker_list,
454 close_marker=self.close_marker,
455 kill_marker=self.kill_marker,
456 send_with_newline=self.send_with_newline,
457 timeout=self.timeout,
458 )
459 self.results = Results(
460 proc_results[0],
461 proc_results[1],
462 proc.returncode,
463 None,
464 expect_stderr=self.expect_stderr,
465 expect_nonzero_exit=self.kill_marker is not None,
466 )
467 except subprocess.TimeoutExpired as ex:
468 print(f"{communicator.name}: TIMEOUT. Killing process.")
469 proc.kill()
470 wrapped_ex = TimeoutException(ex)
471
472 # Read any remaining output
473 print(f"{communicator.name}: TIMEOUT. Reading remaining output.")
474 proc_results = communicator.communicate()
475 self.results = Results(
476 proc_results[0],
477 proc_results[1],
478 proc.returncode,
479 wrapped_ex,
480 self.expect_stderr,
481 )
482 except Exception as ex:
483 self.results = Results(
484 proc_results[0],
485 proc_results[1],
486 proc.returncode,
487 ex,
488 self.expect_stderr,
489 )
490 raise ex
491
492 def kill(self):
493 self.proc.kill()
494
495 def _process_ready(self):
496 """Condition variable predicate"""
497 return self.process_ready is True
498
499 def _results_ready(self):
500 """Condition variable predicate"""
501 return self.results is not None
502
503 def get_cmd_line(self):
504 return self.cmd_line
505
506 def launch(self):
507 """
508 This method must be implemented by the subclass.
509 It should call the run function.
510 """
511 raise NotImplementedError
512
513 def get_results(self, send_data=None):
514 """
515 Block until the results are ready, or a timeout is reached.
516 Return the results, or raise the timeout exception.
517 """
518 with self.results_condition:
519 result = self.results_condition.wait_for(
520 self._results_ready, timeout=self.timeout
521 )
522
523 if result is False:
524 raise Exception("Timeout")
525
526 yield self.results