execute.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. import collections
  2. import enum
  3. import logging
  4. import os
  5. import select
  6. import subprocess
  7. logger = logging.getLogger(__name__)
  8. ERROR_OUTPUT_MAX_LINE_COUNT = 25
  9. BORG_ERROR_EXIT_CODE_START = 2
  10. BORG_ERROR_EXIT_CODE_END = 99
  11. class Exit_status(enum.Enum):
  12. STILL_RUNNING = 1
  13. SUCCESS = 2
  14. WARNING = 3
  15. ERROR = 4
  16. def interpret_exit_code(command, exit_code, borg_local_path=None, borg_exit_codes=None):
  17. '''
  18. Return an Exit_status value (e.g. SUCCESS, ERROR, or WARNING) based on interpreting the given
  19. exit code. If a Borg local path is given and matches the process' command, then interpret the
  20. exit code based on Borg's documented exit code semantics. And if Borg exit codes are given as a
  21. sequence of exit code configuration dicts, then take those configured preferences into account.
  22. '''
  23. if exit_code is None:
  24. return Exit_status.STILL_RUNNING
  25. if exit_code == 0:
  26. return Exit_status.SUCCESS
  27. if borg_local_path and command[0] == borg_local_path:
  28. # First try looking for the exit code in the borg_exit_codes configuration.
  29. for entry in borg_exit_codes or ():
  30. if entry.get('code') == exit_code:
  31. treat_as = entry.get('treat_as')
  32. if treat_as == 'error':
  33. logger.error(
  34. f'Treating exit code {exit_code} as an error, as per configuration'
  35. )
  36. return Exit_status.ERROR
  37. elif treat_as == 'warning':
  38. logger.warning(
  39. f'Treating exit code {exit_code} as a warning, as per configuration'
  40. )
  41. return Exit_status.WARNING
  42. # If the exit code doesn't have explicit configuration, then fall back to the default Borg
  43. # behavior.
  44. return (
  45. Exit_status.ERROR
  46. if (
  47. exit_code < 0
  48. or (
  49. exit_code >= BORG_ERROR_EXIT_CODE_START
  50. and exit_code <= BORG_ERROR_EXIT_CODE_END
  51. )
  52. )
  53. else Exit_status.WARNING
  54. )
  55. return Exit_status.ERROR
  56. def command_for_process(process):
  57. '''
  58. Given a process as an instance of subprocess.Popen, return the command string that was used to
  59. invoke it.
  60. '''
  61. return process.args if isinstance(process.args, str) else ' '.join(process.args)
  62. def output_buffer_for_process(process, exclude_stdouts):
  63. '''
  64. Given a process as an instance of subprocess.Popen and a sequence of stdouts to exclude, return
  65. either the process's stdout or stderr. The idea is that if stdout is excluded for a process, we
  66. still have stderr to log.
  67. '''
  68. return process.stderr if process.stdout in exclude_stdouts else process.stdout
  69. def append_last_lines(last_lines, captured_output, line, output_log_level):
  70. '''
  71. Given a rolling list of last lines, a list of captured output, a line to append, and an output
  72. log level, append the line to the last lines and (if necessary) the captured output. Then log
  73. the line at the requested output log level.
  74. '''
  75. last_lines.append(line)
  76. if len(last_lines) > ERROR_OUTPUT_MAX_LINE_COUNT:
  77. last_lines.pop(0)
  78. if output_log_level is None:
  79. captured_output.append(line)
  80. else:
  81. logger.log(output_log_level, line)
  82. def log_outputs(processes, exclude_stdouts, output_log_level, borg_local_path, borg_exit_codes):
  83. '''
  84. Given a sequence of subprocess.Popen() instances for multiple processes, log the output for each
  85. process with the requested log level. Additionally, raise a CalledProcessError if a process
  86. exits with an error (or a warning for exit code 1, if that process does not match the Borg local
  87. path).
  88. If output log level is None, then instead of logging, capture output for each process and return
  89. it as a dict from the process to its output. Use the given Borg local path and exit code
  90. configuration to decide what's an error and what's a warning.
  91. For simplicity, it's assumed that the output buffer for each process is its stdout. But if any
  92. stdouts are given to exclude, then for any matching processes, log from their stderr instead.
  93. Note that stdout for a process can be None if output is intentionally not captured. In which
  94. case it won't be logged.
  95. '''
  96. # Map from output buffer to sequence of last lines.
  97. buffer_last_lines = collections.defaultdict(list)
  98. process_for_output_buffer = {
  99. output_buffer_for_process(process, exclude_stdouts): process
  100. for process in processes
  101. if process.stdout or process.stderr
  102. }
  103. output_buffers = list(process_for_output_buffer.keys())
  104. captured_outputs = collections.defaultdict(list)
  105. still_running = True
  106. # Log output for each process until they all exit.
  107. while True:
  108. if output_buffers:
  109. (ready_buffers, _, _) = select.select(output_buffers, [], [])
  110. for ready_buffer in ready_buffers:
  111. ready_process = process_for_output_buffer.get(ready_buffer)
  112. # The "ready" process has exited, but it might be a pipe destination with other
  113. # processes (pipe sources) waiting to be read from. So as a measure to prevent
  114. # hangs, vent all processes when one exits.
  115. if ready_process and ready_process.poll() is not None:
  116. for other_process in processes:
  117. if (
  118. other_process.poll() is None
  119. and other_process.stdout
  120. and other_process.stdout not in output_buffers
  121. ):
  122. # Add the process's output to output_buffers to ensure it'll get read.
  123. output_buffers.append(other_process.stdout)
  124. while True:
  125. line = ready_buffer.readline().rstrip().decode()
  126. if not line or not ready_process:
  127. break
  128. # Keep the last few lines of output in case the process errors, and we need the output for
  129. # the exception below.
  130. append_last_lines(
  131. buffer_last_lines[ready_buffer],
  132. captured_outputs[ready_process],
  133. line,
  134. output_log_level,
  135. )
  136. if not still_running:
  137. break
  138. still_running = False
  139. for process in processes:
  140. exit_code = process.poll() if output_buffers else process.wait()
  141. if exit_code is None:
  142. still_running = True
  143. command = process.args.split(' ') if isinstance(process.args, str) else process.args
  144. continue
  145. command = process.args.split(' ') if isinstance(process.args, str) else process.args
  146. exit_status = interpret_exit_code(command, exit_code, borg_local_path, borg_exit_codes)
  147. if exit_status in (Exit_status.ERROR, Exit_status.WARNING):
  148. # If an error occurs, include its output in the raised exception so that we don't
  149. # inadvertently hide error output.
  150. output_buffer = output_buffer_for_process(process, exclude_stdouts)
  151. last_lines = buffer_last_lines[output_buffer] if output_buffer else []
  152. # Collect any straggling output lines that came in since we last gathered output.
  153. while output_buffer: # pragma: no cover
  154. line = output_buffer.readline().rstrip().decode()
  155. if not line:
  156. break
  157. append_last_lines(
  158. last_lines, captured_outputs[process], line, output_log_level=logging.ERROR
  159. )
  160. if len(last_lines) == ERROR_OUTPUT_MAX_LINE_COUNT:
  161. last_lines.insert(0, '...')
  162. # Something has gone wrong. So vent each process' output buffer to prevent it from
  163. # hanging. And then kill the process.
  164. for other_process in processes:
  165. if other_process.poll() is None:
  166. other_process.stdout.read(0)
  167. other_process.kill()
  168. if exit_status == Exit_status.ERROR:
  169. raise subprocess.CalledProcessError(
  170. exit_code, command_for_process(process), '\n'.join(last_lines)
  171. )
  172. still_running = False
  173. break
  174. if captured_outputs:
  175. return {
  176. process: '\n'.join(output_lines) for process, output_lines in captured_outputs.items()
  177. }
  178. def log_command(full_command, input_file=None, output_file=None, environment=None):
  179. '''
  180. Log the given command (a sequence of command/argument strings), along with its input/output file
  181. paths and extra environment variables (with omitted values in case they contain passwords).
  182. '''
  183. logger.debug(
  184. ' '.join(tuple(f'{key}=***' for key in (environment or {}).keys()) + tuple(full_command))
  185. + (f" < {getattr(input_file, 'name', '')}" if input_file else '')
  186. + (f" > {getattr(output_file, 'name', '')}" if output_file else '')
  187. )
  188. # A sentinel passed as an output file to execute_command() to indicate that the command's output
  189. # should be allowed to flow through to stdout without being captured for logging. Useful for
  190. # commands with interactive prompts or those that mess directly with the console.
  191. DO_NOT_CAPTURE = object()
  192. def execute_command(
  193. full_command,
  194. output_log_level=logging.INFO,
  195. output_file=None,
  196. input_file=None,
  197. shell=False,
  198. extra_environment=None,
  199. working_directory=None,
  200. borg_local_path=None,
  201. borg_exit_codes=None,
  202. run_to_completion=True,
  203. ):
  204. '''
  205. Execute the given command (a sequence of command/argument strings) and log its output at the
  206. given log level. If an open output file object is given, then write stdout to the file and only
  207. log stderr. If an open input file object is given, then read stdin from the file. If shell is
  208. True, execute the command within a shell. If an extra environment dict is given, then use it to
  209. augment the current environment, and pass the result into the command. If a working directory is
  210. given, use that as the present working directory when running the command. If a Borg local path
  211. is given, and the command matches it (regardless of arguments), treat exit code 1 as a warning
  212. instead of an error. But if Borg exit codes are given as a sequence of exit code configuration
  213. dicts, then use that configuration to decide what's an error and what's a warning. If run to
  214. completion is False, then return the process for the command without executing it to completion.
  215. Raise subprocesses.CalledProcessError if an error occurs while running the command.
  216. '''
  217. log_command(full_command, input_file, output_file, extra_environment)
  218. environment = {**os.environ, **extra_environment} if extra_environment else None
  219. do_not_capture = bool(output_file is DO_NOT_CAPTURE)
  220. command = ' '.join(full_command) if shell else full_command
  221. process = subprocess.Popen(
  222. command,
  223. stdin=input_file,
  224. stdout=None if do_not_capture else (output_file or subprocess.PIPE),
  225. stderr=None if do_not_capture else (subprocess.PIPE if output_file else subprocess.STDOUT),
  226. shell=shell,
  227. env=environment,
  228. cwd=working_directory,
  229. )
  230. if not run_to_completion:
  231. return process
  232. log_outputs(
  233. (process,),
  234. (input_file, output_file),
  235. output_log_level,
  236. borg_local_path,
  237. borg_exit_codes,
  238. )
  239. def execute_command_and_capture_output(
  240. full_command,
  241. capture_stderr=False,
  242. shell=False,
  243. extra_environment=None,
  244. working_directory=None,
  245. borg_local_path=None,
  246. borg_exit_codes=None,
  247. ):
  248. '''
  249. Execute the given command (a sequence of command/argument strings), capturing and returning its
  250. output (stdout). If capture stderr is True, then capture and return stderr in addition to
  251. stdout. If shell is True, execute the command within a shell. If an extra environment dict is
  252. given, then use it to augment the current environment, and pass the result into the command. If
  253. a working directory is given, use that as the present working directory when running the
  254. command. If a Borg local path is given, and the command matches it (regardless of arguments),
  255. treat exit code 1 as a warning instead of an error. But if Borg exit codes are given as a
  256. sequence of exit code configuration dicts, then use that configuration to decide what's an error
  257. and what's a warning.
  258. Raise subprocesses.CalledProcessError if an error occurs while running the command.
  259. '''
  260. log_command(full_command, environment=extra_environment)
  261. environment = {**os.environ, **extra_environment} if extra_environment else None
  262. command = ' '.join(full_command) if shell else full_command
  263. try:
  264. output = subprocess.check_output(
  265. command,
  266. stderr=subprocess.STDOUT if capture_stderr else None,
  267. shell=shell,
  268. env=environment,
  269. cwd=working_directory,
  270. )
  271. except subprocess.CalledProcessError as error:
  272. if (
  273. interpret_exit_code(command, error.returncode, borg_local_path, borg_exit_codes)
  274. == Exit_status.ERROR
  275. ):
  276. raise
  277. output = error.output
  278. return output.decode() if output is not None else None
  279. def execute_command_with_processes(
  280. full_command,
  281. processes,
  282. output_log_level=logging.INFO,
  283. output_file=None,
  284. input_file=None,
  285. shell=False,
  286. extra_environment=None,
  287. working_directory=None,
  288. borg_local_path=None,
  289. borg_exit_codes=None,
  290. ):
  291. '''
  292. Execute the given command (a sequence of command/argument strings) and log its output at the
  293. given log level. Simultaneously, continue to poll one or more active processes so that they
  294. run as well. This is useful, for instance, for processes that are streaming output to a named
  295. pipe that the given command is consuming from.
  296. If an open output file object is given, then write stdout to the file and only log stderr. But
  297. if output log level is None, instead suppress logging and return the captured output for (only)
  298. the given command. If an open input file object is given, then read stdin from the file. If
  299. shell is True, execute the command within a shell. If an extra environment dict is given, then
  300. use it to augment the current environment, and pass the result into the command. If a working
  301. directory is given, use that as the present working directory when running the command. If a
  302. Borg local path is given, then for any matching command or process (regardless of arguments),
  303. treat exit code 1 as a warning instead of an error. But if Borg exit codes are given as a
  304. sequence of exit code configuration dicts, then use that configuration to decide what's an error
  305. and what's a warning.
  306. Raise subprocesses.CalledProcessError if an error occurs while running the command or in the
  307. upstream process.
  308. '''
  309. log_command(full_command, input_file, output_file, extra_environment)
  310. environment = {**os.environ, **extra_environment} if extra_environment else None
  311. do_not_capture = bool(output_file is DO_NOT_CAPTURE)
  312. command = ' '.join(full_command) if shell else full_command
  313. try:
  314. command_process = subprocess.Popen(
  315. command,
  316. stdin=input_file,
  317. stdout=None if do_not_capture else (output_file or subprocess.PIPE),
  318. stderr=None
  319. if do_not_capture
  320. else (subprocess.PIPE if output_file else subprocess.STDOUT),
  321. shell=shell,
  322. env=environment,
  323. cwd=working_directory,
  324. )
  325. except (subprocess.CalledProcessError, OSError):
  326. # Something has gone wrong. So vent each process' output buffer to prevent it from hanging.
  327. # And then kill the process.
  328. for process in processes:
  329. if process.poll() is None:
  330. process.stdout.read(0)
  331. process.kill()
  332. raise
  333. captured_outputs = log_outputs(
  334. tuple(processes) + (command_process,),
  335. (input_file, output_file),
  336. output_log_level,
  337. borg_local_path,
  338. borg_exit_codes,
  339. )
  340. if output_log_level is None:
  341. return captured_outputs.get(command_process)