Debian Codegraph @

cylc/flow/pipe_poller.py

raw
1 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
2 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 """Utility for preventing pipes from getting clogged up.
18
19 If you're reading files from Popen (i.e. to extract command output) where the
20 command output has the potential to be long-ish, then you should use this
21 function to protect against the buffer filling up.
22
23 Note, there is a more advanced version of this baked into the subprocpool.
24 """
25
26 import selectors
27 from typing import (
28 IO,
29 TYPE_CHECKING,
30 TypeVar,
31 cast,
32 )
33
34
35 if TYPE_CHECKING:
36 from subprocess import Popen
37
38
39 T = TypeVar('T', str, bytes)
40
41
42 def pipe_poller(
43 proc: 'Popen[T]', *files: IO[T], chunk_size=4096
44 ) -> tuple[T, ...]:
45 """Read from a process without hitting buffer issues.
46
47 Standin for subprocess.Popen.communicate.
48
49 When PIPE'ing from subprocesses, the output goes into a buffer. If the
50 buffer gets full, the subprocess will hang trying to write to it.
51
52 This function polls the process, reading output from the buffers into
53 memory to prevent them from filling up.
54
55 Args:
56 proc:
57 The process to poll.
58 files:
59 The files you want to read from, likely anything you've directed to
60 PIPE.
61 chunk_size:
62 The amount of text to read from the buffer on each pass.
63
64 Returns:
65 tuple - The text read from each of the files in the order they were
66 specified.
67
68 """
69
70 selector = selectors.DefaultSelector()
71 file_to_output: dict[IO[T], T] = {}
72 for file in files:
73 file_to_output[file] = file.read(0) # empty str | bytes
74 selector.register(file, selectors.EVENT_READ)
75
76 def _read(timeout=1.0):
77 # read any data from files
78 for key, _events in selector.select(timeout):
79 file = cast('IO[T]', key.fileobj)
80 buffer = file.read(chunk_size)
81 if len(buffer) > 0:
82 file_to_output[file] += buffer
83
84 while proc.poll() is None:
85 # read from the buffers
86 _read()
87 # double check the buffers now that the process has finished
88 _read(timeout=0.01)
89
90 selector.close()
91 return tuple(file_to_output.values())