subprocess.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. # Licensed to the Apache Software Foundation (ASF) under one
  2. # or more contributor license agreements. See the NOTICE file
  3. # distributed with this work for additional information
  4. # regarding copyright ownership. The ASF licenses this file
  5. # to you under the Apache License, Version 2.0 (the
  6. # "License"); you may not use this file except in compliance
  7. # with the License. You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing,
  12. # software distributed under the License is distributed on an
  13. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. # KIND, either express or implied. See the License for the
  15. # specific language governing permissions and limitations
  16. # under the License.
  17. from __future__ import annotations
  18. import contextlib
  19. import os
  20. import signal
  21. from collections import namedtuple
  22. from subprocess import PIPE, STDOUT, Popen
  23. from tempfile import TemporaryDirectory, gettempdir
  24. from typing import Iterator
  25. from airflow.hooks.base import BaseHook
  26. SubprocessResult = namedtuple("SubprocessResult", ["exit_code", "output"])
  27. @contextlib.contextmanager
  28. def working_directory(cwd: str | None = None) -> Iterator[str]:
  29. """
  30. Context manager for handling (temporary) working directory.
  31. Use the given cwd as working directory, if provided.
  32. Otherwise, create a temporary directory.
  33. """
  34. with contextlib.ExitStack() as stack:
  35. if cwd is None:
  36. cwd = stack.enter_context(TemporaryDirectory(prefix="airflowtmp"))
  37. yield cwd
  38. class SubprocessHook(BaseHook):
  39. """Hook for running processes with the ``subprocess`` module."""
  40. def __init__(self, **kwargs) -> None:
  41. self.sub_process: Popen[bytes] | None = None
  42. super().__init__(**kwargs)
  43. def run_command(
  44. self,
  45. command: list[str],
  46. env: dict[str, str] | None = None,
  47. output_encoding: str = "utf-8",
  48. cwd: str | None = None,
  49. ) -> SubprocessResult:
  50. """
  51. Execute the command.
  52. If ``cwd`` is None, execute the command in a temporary directory which will be cleaned afterwards.
  53. If ``env`` is not supplied, ``os.environ`` is passed
  54. :param command: the command to run
  55. :param env: Optional dict containing environment variables to be made available to the shell
  56. environment in which ``command`` will be executed. If omitted, ``os.environ`` will be used.
  57. Note, that in case you have Sentry configured, original variables from the environment
  58. will also be passed to the subprocess with ``SUBPROCESS_`` prefix. See
  59. :doc:`/administration-and-deployment/logging-monitoring/errors` for details.
  60. :param output_encoding: encoding to use for decoding stdout
  61. :param cwd: Working directory to run the command in.
  62. If None (default), the command is run in a temporary directory.
  63. :return: :class:`namedtuple` containing ``exit_code`` and ``output``, the last line from stderr
  64. or stdout
  65. """
  66. self.log.info("Tmp dir root location: %s", gettempdir())
  67. with working_directory(cwd=cwd) as cwd:
  68. def pre_exec():
  69. # Restore default signal disposition and invoke setsid
  70. for sig in ("SIGPIPE", "SIGXFZ", "SIGXFSZ"):
  71. if hasattr(signal, sig):
  72. signal.signal(getattr(signal, sig), signal.SIG_DFL)
  73. os.setsid()
  74. self.log.info("Running command: %s", command)
  75. self.sub_process = Popen(
  76. command,
  77. stdout=PIPE,
  78. stderr=STDOUT,
  79. cwd=cwd,
  80. env=env if env or env == {} else os.environ,
  81. preexec_fn=pre_exec,
  82. )
  83. self.log.info("Output:")
  84. line = ""
  85. if self.sub_process is None:
  86. raise RuntimeError("The subprocess should be created here and is None!")
  87. if self.sub_process.stdout is not None:
  88. for raw_line in iter(self.sub_process.stdout.readline, b""):
  89. line = raw_line.decode(output_encoding, errors="backslashreplace").rstrip()
  90. self.log.info("%s", line)
  91. self.sub_process.wait()
  92. self.log.info("Command exited with return code %s", self.sub_process.returncode)
  93. return_code: int = self.sub_process.returncode
  94. return SubprocessResult(exit_code=return_code, output=line)
  95. def send_sigterm(self):
  96. """Send SIGTERM signal to ``self.sub_process`` if one exists."""
  97. self.log.info("Sending SIGTERM signal to process group")
  98. if self.sub_process and hasattr(self.sub_process, "pid"):
  99. os.killpg(os.getpgid(self.sub_process.pid), signal.SIGTERM)