| 168 | # TODO: Now that we support Python >= 3.6 we should utilize timeout argument for the |
| 169 | # communicate() method and handle killing the process + read threads there. |
| 170 | def on_timeout_expired(timeout): |
| 171 | global timed_out |
| 172 | |
| 173 | try: |
| 174 | LOG.debug("Starting process wait inside timeout handler.") |
| 175 | process.wait(timeout=timeout) |
| 176 | except subprocess.TimeoutExpired: |
| 177 | # Command has timed out, kill the process and propagate the error. |
| 178 | # Note: We explicitly set the returncode to indicate the timeout. |
| 179 | LOG.debug("Command execution timeout reached.") |
| 180 | |
| 181 | process._timed_out = True |
| 182 | |
| 183 | if kill_func: |
| 184 | LOG.debug("Calling kill_func.") |
| 185 | kill_func(process=process) |
| 186 | else: |
| 187 | LOG.debug("Killing process.") |
| 188 | process.kill() |
| 189 | |
| 190 | process.wait() |
| 191 | process._timed_out = True |
| 192 | |
| 193 | if read_stdout_func and read_stderr_func: |
| 194 | LOG.debug("Killing read_stdout_thread and read_stderr_thread") |
| 195 | concurrency.kill(read_stdout_thread) |
| 196 | concurrency.kill(read_stderr_thread) |
| 197 | |
| 198 | LOG.debug("Spawning timeout handler thread.") |
| 199 | timeout_thread = concurrency.spawn(on_timeout_expired, timeout) |