bash.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. #
  2. # Licensed to the Apache Software Foundation (ASF) under one
  3. # or more contributor license agreements. See the NOTICE file
  4. # distributed with this work for additional information
  5. # regarding copyright ownership. The ASF licenses this file
  6. # to you under the Apache License, Version 2.0 (the
  7. # "License"); you may not use this file except in compliance
  8. # with the License. You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing,
  13. # software distributed under the License is distributed on an
  14. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. # KIND, either express or implied. See the License for the
  16. # specific language governing permissions and limitations
  17. # under the License.
  18. from __future__ import annotations
  19. import os
  20. import shutil
  21. import tempfile
  22. import warnings
  23. from functools import cached_property
  24. from typing import TYPE_CHECKING, Any, Callable, Container, Sequence, cast
  25. from airflow.exceptions import AirflowException, AirflowSkipException, RemovedInAirflow3Warning
  26. from airflow.hooks.subprocess import SubprocessHook, SubprocessResult, working_directory
  27. from airflow.models.baseoperator import BaseOperator
  28. from airflow.utils.operator_helpers import context_to_airflow_vars
  29. from airflow.utils.types import ArgNotSet
  30. if TYPE_CHECKING:
  31. from airflow.models.taskinstance import TaskInstance
  32. from airflow.utils.context import Context
  33. class BashOperator(BaseOperator):
  34. r"""
  35. Execute a Bash script, command or set of commands.
  36. .. seealso::
  37. For more information on how to use this operator, take a look at the guide:
  38. :ref:`howto/operator:BashOperator`
  39. If BaseOperator.do_xcom_push is True, the last line written to stdout
  40. will also be pushed to an XCom when the bash command completes
  41. :param bash_command: The command, set of commands or reference to a
  42. Bash script (must be '.sh' or '.bash') to be executed. (templated)
  43. :param env: If env is not None, it must be a dict that defines the
  44. environment variables for the new process; these are used instead
  45. of inheriting the current process environment, which is the default
  46. behavior. (templated)
  47. :param append_env: If False(default) uses the environment variables passed in env params
  48. and does not inherit the current process environment. If True, inherits the environment variables
  49. from current passes and then environment variable passed by the user will either update the existing
  50. inherited environment variables or the new variables gets appended to it
  51. :param output_encoding: Output encoding of Bash command
  52. :param skip_on_exit_code: If task exits with this exit code, leave the task
  53. in ``skipped`` state (default: 99). If set to ``None``, any non-zero
  54. exit code will be treated as a failure.
  55. :param cwd: Working directory to execute the command in (templated).
  56. If None (default), the command is run in a temporary directory.
  57. To use current DAG folder as the working directory,
  58. you might set template ``{{ dag_run.dag.folder }}``.
  59. When bash_command is a '.sh' or '.bash' file, Airflow must have write
  60. access to the working directory. The script will be rendered (Jinja
  61. template) into a new temporary file in this directory.
  62. :param output_processor: Function to further process the output of the bash script
  63. (default is lambda output: output).
  64. Airflow will evaluate the exit code of the Bash command. In general, a non-zero exit code will result in
  65. task failure and zero will result in task success.
  66. Exit code ``99`` (or another set in ``skip_on_exit_code``)
  67. will throw an :class:`airflow.exceptions.AirflowSkipException`, which will leave the task in ``skipped``
  68. state. You can have all non-zero exit codes be treated as a failure by setting ``skip_on_exit_code=None``.
  69. .. list-table::
  70. :widths: 25 25
  71. :header-rows: 1
  72. * - Exit code
  73. - Behavior
  74. * - 0
  75. - success
  76. * - `skip_on_exit_code` (default: 99)
  77. - raise :class:`airflow.exceptions.AirflowSkipException`
  78. * - otherwise
  79. - raise :class:`airflow.exceptions.AirflowException`
  80. .. note::
  81. Airflow will not recognize a non-zero exit code unless the whole shell exit with a non-zero exit
  82. code. This can be an issue if the non-zero exit arises from a sub-command. The easiest way of
  83. addressing this is to prefix the command with ``set -e;``
  84. .. code-block:: python
  85. bash_command = "set -e; python3 script.py '{{ next_execution_date }}'"
  86. .. note::
  87. To simply execute a ``.sh`` or ``.bash`` script (without any Jinja template), add a space after the
  88. script name ``bash_command`` argument -- for example ``bash_command="my_script.sh "``. This
  89. is because Airflow tries to load this file and process it as a Jinja template when
  90. it ends with ``.sh`` or ``.bash``.
  91. If you have Jinja template in your script, do not put any blank space. And add the script's directory
  92. in the DAG's ``template_searchpath``. If you specify a ``cwd``, Airflow must have write access to
  93. this directory. The script will be rendered (Jinja template) into a new temporary file in this directory.
  94. .. warning::
  95. Care should be taken with "user" input or when using Jinja templates in the
  96. ``bash_command``, as this bash operator does not perform any escaping or
  97. sanitization of the command.
  98. This applies mostly to using "dag_run" conf, as that can be submitted via
  99. users in the Web UI. Most of the default template variables are not at
  100. risk.
  101. For example, do **not** do this:
  102. .. code-block:: python
  103. bash_task = BashOperator(
  104. task_id="bash_task",
  105. bash_command='echo "Here is the message: \'{{ dag_run.conf["message"] if dag_run else "" }}\'"',
  106. )
  107. Instead, you should pass this via the ``env`` kwarg and use double-quotes
  108. inside the bash_command, as below:
  109. .. code-block:: python
  110. bash_task = BashOperator(
  111. task_id="bash_task",
  112. bash_command="echo \"here is the message: '$message'\"",
  113. env={"message": '{{ dag_run.conf["message"] if dag_run else "" }}'},
  114. )
  115. .. versionadded:: 2.10.0
  116. The `output_processor` parameter.
  117. """
  118. template_fields: Sequence[str] = ("bash_command", "env", "cwd")
  119. template_fields_renderers = {"bash_command": "bash", "env": "json"}
  120. template_ext: Sequence[str] = (".sh", ".bash")
  121. ui_color = "#f0ede4"
  122. def __init__(
  123. self,
  124. *,
  125. bash_command: str | ArgNotSet,
  126. env: dict[str, str] | None = None,
  127. append_env: bool = False,
  128. output_encoding: str = "utf-8",
  129. skip_exit_code: int | None = None,
  130. skip_on_exit_code: int | Container[int] | None = 99,
  131. cwd: str | None = None,
  132. output_processor: Callable[[str], Any] = lambda result: result,
  133. **kwargs,
  134. ) -> None:
  135. super().__init__(**kwargs)
  136. self.bash_command = bash_command
  137. self.env = env
  138. self.output_encoding = output_encoding
  139. if skip_exit_code is not None:
  140. warnings.warn(
  141. "skip_exit_code is deprecated. Please use skip_on_exit_code", DeprecationWarning, stacklevel=2
  142. )
  143. skip_on_exit_code = skip_exit_code
  144. self.skip_on_exit_code = (
  145. skip_on_exit_code
  146. if isinstance(skip_on_exit_code, Container)
  147. else [skip_on_exit_code]
  148. if skip_on_exit_code is not None
  149. else []
  150. )
  151. self.cwd = cwd
  152. self.append_env = append_env
  153. self.output_processor = output_processor
  154. # When using the @task.bash decorator, the Bash command is not known until the underlying Python
  155. # callable is executed and therefore set to NOTSET initially. This flag is useful during execution to
  156. # determine whether the bash_command value needs to re-rendered.
  157. self._init_bash_command_not_set = isinstance(self.bash_command, ArgNotSet)
  158. # Keep a copy of the original bash_command, without the Jinja template rendered.
  159. # This is later used to determine if the bash_command is a script or an inline string command.
  160. # We do this later, because the bash_command is not available in __init__ when using @task.bash.
  161. self._unrendered_bash_command: str | ArgNotSet = bash_command
  162. @cached_property
  163. def subprocess_hook(self):
  164. """Returns hook for running the bash command."""
  165. return SubprocessHook()
  166. @staticmethod
  167. def refresh_bash_command(ti: TaskInstance) -> None:
  168. """
  169. Rewrite the underlying rendered bash_command value for a task instance in the metadatabase.
  170. TaskInstance.get_rendered_template_fields() cannot be used because this will retrieve the
  171. RenderedTaskInstanceFields from the metadatabase which doesn't have the runtime-evaluated bash_command
  172. value.
  173. :meta private:
  174. """
  175. from airflow.models.renderedtifields import RenderedTaskInstanceFields
  176. RenderedTaskInstanceFields._update_runtime_evaluated_template_fields(ti)
  177. def get_env(self, context) -> dict:
  178. """Build the set of environment variables to be exposed for the bash command."""
  179. system_env = os.environ.copy()
  180. env = self.env
  181. if env is None:
  182. env = system_env
  183. else:
  184. if self.append_env:
  185. system_env.update(env)
  186. env = system_env
  187. airflow_context_vars = context_to_airflow_vars(context, in_env_var_format=True)
  188. self.log.debug(
  189. "Exporting env vars: %s",
  190. " ".join(f"{k}={v!r}" for k, v in airflow_context_vars.items()),
  191. )
  192. env.update(airflow_context_vars)
  193. return env
  194. def execute(self, context: Context):
  195. bash_path: str = shutil.which("bash") or "bash"
  196. if self.cwd is not None:
  197. if not os.path.exists(self.cwd):
  198. raise AirflowException(f"Can not find the cwd: {self.cwd}")
  199. if not os.path.isdir(self.cwd):
  200. raise AirflowException(f"The cwd {self.cwd} must be a directory")
  201. env = self.get_env(context)
  202. # Because the bash_command value is evaluated at runtime using the @task.bash decorator, the
  203. # RenderedTaskInstanceField data needs to be rewritten and the bash_command value re-rendered -- the
  204. # latter because the returned command from the decorated callable could contain a Jinja expression.
  205. # Both will ensure the correct Bash command is executed and that the Rendered Template view in the UI
  206. # displays the executed command (otherwise it will display as an ArgNotSet type).
  207. if self._init_bash_command_not_set:
  208. is_inline_command = self._is_inline_command(bash_command=cast(str, self.bash_command))
  209. ti = cast("TaskInstance", context["ti"])
  210. self.refresh_bash_command(ti)
  211. else:
  212. is_inline_command = self._is_inline_command(bash_command=cast(str, self._unrendered_bash_command))
  213. if is_inline_command:
  214. result = self._run_inline_command(bash_path=bash_path, env=env)
  215. else:
  216. try:
  217. result = self._run_rendered_script_file(bash_path=bash_path, env=env)
  218. except PermissionError:
  219. directory: str = self.cwd or tempfile.gettempdir()
  220. warnings.warn(
  221. "BashOperator behavior for script files (`.sh` and `.bash`) containing Jinja templating "
  222. "will change in Airflow 3: script's content will be rendered into a new temporary file, "
  223. "and then executed (instead of being directly executed as inline command). "
  224. f"Ensure Airflow has write and execute permission in the `{directory}` directory.",
  225. RemovedInAirflow3Warning,
  226. stacklevel=2,
  227. )
  228. result = self._run_inline_command(bash_path=bash_path, env=env)
  229. if result.exit_code in self.skip_on_exit_code:
  230. raise AirflowSkipException(f"Bash command returned exit code {result.exit_code}. Skipping.")
  231. elif result.exit_code != 0:
  232. raise AirflowException(
  233. f"Bash command failed. The command returned a non-zero exit code {result.exit_code}."
  234. )
  235. return self.output_processor(result.output)
  236. def _run_inline_command(self, bash_path: str, env: dict) -> SubprocessResult:
  237. """Pass the bash command as string directly in the subprocess."""
  238. return self.subprocess_hook.run_command(
  239. command=[bash_path, "-c", self.bash_command],
  240. env=env,
  241. output_encoding=self.output_encoding,
  242. cwd=self.cwd,
  243. )
  244. def _run_rendered_script_file(self, bash_path: str, env: dict) -> SubprocessResult:
  245. """
  246. Save the bash command into a file and execute this file.
  247. This allows for longer commands, and prevents "Argument list too long error".
  248. """
  249. with working_directory(cwd=self.cwd) as cwd:
  250. with tempfile.NamedTemporaryFile(mode="w", dir=cwd, suffix=".sh") as file:
  251. file.write(cast(str, self.bash_command))
  252. file.flush()
  253. bash_script = os.path.basename(file.name)
  254. return self.subprocess_hook.run_command(
  255. command=[bash_path, bash_script],
  256. env=env,
  257. output_encoding=self.output_encoding,
  258. cwd=cwd,
  259. )
  260. @classmethod
  261. def _is_inline_command(cls, bash_command: str) -> bool:
  262. """Return True if the bash command is an inline string. False if it's a bash script file."""
  263. return not bash_command.endswith(tuple(cls.template_ext))
  264. def on_kill(self) -> None:
  265. self.subprocess_hook.send_sigterm()