execute.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. import collections
  2. import logging
  3. import os
  4. import select
  5. import subprocess
  6. logger = logging.getLogger(__name__)
  7. ERROR_OUTPUT_MAX_LINE_COUNT = 25
  8. BORG_ERROR_EXIT_CODE = 2
  9. def exit_code_indicates_error(process, exit_code, borg_local_path=None):
  10. '''
  11. Return True if the given exit code from running a command corresponds to an error. If a Borg
  12. local path is given and matches the process' command, then treat exit code 1 as a warning
  13. instead of an error.
  14. '''
  15. if exit_code is None:
  16. return False
  17. command = process.args.split(' ') if isinstance(process.args, str) else process.args
  18. if borg_local_path and command[0] == borg_local_path:
  19. return bool(exit_code < 0 or exit_code >= BORG_ERROR_EXIT_CODE)
  20. return bool(exit_code != 0)
  21. def command_for_process(process):
  22. '''
  23. Given a process as an instance of subprocess.Popen, return the command string that was used to
  24. invoke it.
  25. '''
  26. return process.args if isinstance(process.args, str) else ' '.join(process.args)
  27. def output_buffer_for_process(process, exclude_stdouts):
  28. '''
  29. Given a process as an instance of subprocess.Popen and a sequence of stdouts to exclude, return
  30. either the process's stdout or stderr. The idea is that if stdout is excluded for a process, we
  31. still have stderr to log.
  32. '''
  33. return process.stderr if process.stdout in exclude_stdouts else process.stdout
  34. def log_outputs(processes, exclude_stdouts, output_log_level, borg_local_path):
  35. '''
  36. Given a sequence of subprocess.Popen() instances for multiple processes, log the output for each
  37. process with the requested log level. Additionally, raise a CalledProcessError if a process
  38. exits with an error (or a warning for exit code 1, if that process matches the Borg local path).
  39. For simplicity, it's assumed that the output buffer for each process is its stdout. But if any
  40. stdouts are given to exclude, then for any matching processes, log from their stderr instead.
  41. Note that stdout for a process can be None if output is intentionally not captured. In which
  42. case it won't be logged.
  43. '''
  44. # Map from output buffer to sequence of last lines.
  45. buffer_last_lines = collections.defaultdict(list)
  46. process_for_output_buffer = {
  47. output_buffer_for_process(process, exclude_stdouts): process
  48. for process in processes
  49. if process.stdout or process.stderr
  50. }
  51. output_buffers = list(process_for_output_buffer.keys())
  52. # Log output for each process until they all exit.
  53. while True:
  54. if output_buffers:
  55. (ready_buffers, _, _) = select.select(output_buffers, [], [])
  56. for ready_buffer in ready_buffers:
  57. ready_process = process_for_output_buffer.get(ready_buffer)
  58. # The "ready" process has exited, but it might be a pipe destination with other
  59. # processes (pipe sources) waiting to be read from. So as a measure to prevent
  60. # hangs, vent all processes when one exits.
  61. if ready_process and ready_process.poll() is not None:
  62. for other_process in processes:
  63. if (
  64. other_process.poll() is None
  65. and other_process.stdout not in output_buffers
  66. ):
  67. # Add the process's output to output_buffers to ensure it'll get read.
  68. output_buffers.append(other_process.stdout)
  69. line = ready_buffer.readline().rstrip().decode()
  70. if not line or not ready_process:
  71. continue
  72. # Keep the last few lines of output in case the process errors, and we need the output for
  73. # the exception below.
  74. last_lines = buffer_last_lines[ready_buffer]
  75. last_lines.append(line)
  76. if len(last_lines) > ERROR_OUTPUT_MAX_LINE_COUNT:
  77. last_lines.pop(0)
  78. logger.log(output_log_level, line)
  79. still_running = False
  80. for process in processes:
  81. exit_code = process.poll() if output_buffers else process.wait()
  82. if exit_code is None:
  83. still_running = True
  84. # If any process errors, then raise accordingly.
  85. if exit_code_indicates_error(process, exit_code, borg_local_path):
  86. # If an error occurs, include its output in the raised exception so that we don't
  87. # inadvertently hide error output.
  88. output_buffer = output_buffer_for_process(process, exclude_stdouts)
  89. last_lines = buffer_last_lines[output_buffer] if output_buffer else []
  90. if len(last_lines) == ERROR_OUTPUT_MAX_LINE_COUNT:
  91. last_lines.insert(0, '...')
  92. # Something has gone wrong. So vent each process' output buffer to prevent it from
  93. # hanging. And then kill the process.
  94. for other_process in processes:
  95. if other_process.poll() is None:
  96. other_process.stdout.read(0)
  97. other_process.kill()
  98. raise subprocess.CalledProcessError(
  99. exit_code, command_for_process(process), '\n'.join(last_lines)
  100. )
  101. if not still_running:
  102. break
  103. # Consume any remaining output that we missed (if any).
  104. for process in processes:
  105. output_buffer = output_buffer_for_process(process, exclude_stdouts)
  106. if not output_buffer:
  107. continue
  108. remaining_output = output_buffer.read().rstrip().decode()
  109. if remaining_output: # pragma: no cover
  110. logger.log(output_log_level, remaining_output)
  111. def log_command(full_command, input_file, output_file):
  112. '''
  113. Log the given command (a sequence of command/argument strings), along with its input/output file
  114. paths.
  115. '''
  116. logger.debug(
  117. ' '.join(full_command)
  118. + (' < {}'.format(getattr(input_file, 'name', '')) if input_file else '')
  119. + (' > {}'.format(getattr(output_file, 'name', '')) if output_file else '')
  120. )
  121. # An sentinel passed as an output file to execute_command() to indicate that the command's output
  122. # should be allowed to flow through to stdout without being captured for logging. Useful for
  123. # commands with interactive prompts or those that mess directly with the console.
  124. DO_NOT_CAPTURE = object()
  125. def execute_command(
  126. full_command,
  127. output_log_level=logging.INFO,
  128. output_file=None,
  129. input_file=None,
  130. shell=False,
  131. extra_environment=None,
  132. working_directory=None,
  133. borg_local_path=None,
  134. run_to_completion=True,
  135. ):
  136. '''
  137. Execute the given command (a sequence of command/argument strings) and log its output at the
  138. given log level. If output log level is None, instead capture and return the output. (Implies
  139. run_to_completion.) If an open output file object is given, then write stdout to the file and
  140. only log stderr (but only if an output log level is set). If an open input file object is given,
  141. then read stdin from the file. If shell is True, execute the command within a shell. If an extra
  142. environment dict is given, then use it to augment the current environment, and pass the result
  143. into the command. If a working directory is given, use that as the present working directory
  144. when running the command. If a Borg local path is given, and the command matches it (regardless
  145. of arguments), treat exit code 1 as a warning instead of an error. If run to completion is
  146. False, then return the process for the command without executing it to completion.
  147. Raise subprocesses.CalledProcessError if an error occurs while running the command.
  148. '''
  149. log_command(full_command, input_file, output_file)
  150. environment = {**os.environ, **extra_environment} if extra_environment else None
  151. do_not_capture = bool(output_file is DO_NOT_CAPTURE)
  152. command = ' '.join(full_command) if shell else full_command
  153. if output_log_level is None:
  154. output = subprocess.check_output(
  155. command, shell=shell, env=environment, cwd=working_directory
  156. )
  157. return output.decode() if output is not None else None
  158. process = subprocess.Popen(
  159. command,
  160. stdin=input_file,
  161. stdout=None if do_not_capture else (output_file or subprocess.PIPE),
  162. stderr=None if do_not_capture else (subprocess.PIPE if output_file else subprocess.STDOUT),
  163. shell=shell,
  164. env=environment,
  165. cwd=working_directory,
  166. )
  167. if not run_to_completion:
  168. return process
  169. log_outputs(
  170. (process,), (input_file, output_file), output_log_level, borg_local_path=borg_local_path
  171. )
  172. def execute_command_with_processes(
  173. full_command,
  174. processes,
  175. output_log_level=logging.INFO,
  176. output_file=None,
  177. input_file=None,
  178. shell=False,
  179. extra_environment=None,
  180. working_directory=None,
  181. borg_local_path=None,
  182. ):
  183. '''
  184. Execute the given command (a sequence of command/argument strings) and log its output at the
  185. given log level. Simultaneously, continue to poll one or more active processes so that they
  186. run as well. This is useful, for instance, for processes that are streaming output to a named
  187. pipe that the given command is consuming from.
  188. If an open output file object is given, then write stdout to the file and only log stderr (but
  189. only if an output log level is set). If an open input file object is given, then read stdin from
  190. the file. If shell is True, execute the command within a shell. If an extra environment dict is
  191. given, then use it to augment the current environment, and pass the result into the command. If
  192. a working directory is given, use that as the present working directory when running the
  193. command. If a Borg local path is given, then for any matching command or process (regardless of
  194. arguments), treat exit code 1 as a warning instead of an error.
  195. Raise subprocesses.CalledProcessError if an error occurs while running the command or in the
  196. upstream process.
  197. '''
  198. log_command(full_command, input_file, output_file)
  199. environment = {**os.environ, **extra_environment} if extra_environment else None
  200. do_not_capture = bool(output_file is DO_NOT_CAPTURE)
  201. command = ' '.join(full_command) if shell else full_command
  202. try:
  203. command_process = subprocess.Popen(
  204. command,
  205. stdin=input_file,
  206. stdout=None if do_not_capture else (output_file or subprocess.PIPE),
  207. stderr=None
  208. if do_not_capture
  209. else (subprocess.PIPE if output_file else subprocess.STDOUT),
  210. shell=shell,
  211. env=environment,
  212. cwd=working_directory,
  213. )
  214. except (subprocess.CalledProcessError, OSError):
  215. # Something has gone wrong. So vent each process' output buffer to prevent it from hanging.
  216. # And then kill the process.
  217. for process in processes:
  218. if process.poll() is None:
  219. process.stdout.read(0)
  220. process.kill()
  221. raise
  222. log_outputs(
  223. tuple(processes) + (command_process,),
  224. (input_file, output_file),
  225. output_log_level,
  226. borg_local_path=borg_local_path,
  227. )