apache-airflow-providers-standard 1.0.0.dev0__py3-none-any.whl → 1.0.0.dev1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of apache-airflow-providers-standard might be problematic. Click here for more details.

@@ -45,6 +45,7 @@ def get_provider_info():
45
45
  "python-modules": [
46
46
  "airflow.providers.standard.operators.datetime",
47
47
  "airflow.providers.standard.operators.weekday",
48
+ "airflow.providers.standard.operators.bash",
48
49
  ],
49
50
  }
50
51
  ],
@@ -56,6 +57,7 @@ def get_provider_info():
56
57
  "airflow.providers.standard.sensors.time_delta",
57
58
  "airflow.providers.standard.sensors.time",
58
59
  "airflow.providers.standard.sensors.weekday",
60
+ "airflow.providers.standard.sensors.bash",
59
61
  ],
60
62
  }
61
63
  ],
@@ -0,0 +1,256 @@
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
+
20
+ import os
21
+ import shutil
22
+ import warnings
23
+ from functools import cached_property
24
+ from typing import TYPE_CHECKING, Any, Callable, Container, Sequence, cast
25
+
26
+ from airflow.exceptions import AirflowException, AirflowSkipException
27
+ from airflow.hooks.subprocess import SubprocessHook
28
+ from airflow.models.baseoperator import BaseOperator
29
+ from airflow.utils.operator_helpers import context_to_airflow_vars
30
+ from airflow.utils.types import ArgNotSet
31
+
32
+ if TYPE_CHECKING:
33
+ from airflow.models.taskinstance import TaskInstance
34
+ from airflow.utils.context import Context
35
+
36
+
37
+ class BashOperator(BaseOperator):
38
+ r"""
39
+ Execute a Bash script, command or set of commands.
40
+
41
+ .. seealso::
42
+ For more information on how to use this operator, take a look at the guide:
43
+ :ref:`howto/operator:BashOperator`
44
+
45
+ If BaseOperator.do_xcom_push is True, the last line written to stdout
46
+ will also be pushed to an XCom when the bash command completes
47
+
48
+ :param bash_command: The command, set of commands or reference to a
49
+ Bash script (must be '.sh' or '.bash') to be executed. (templated)
50
+ :param env: If env is not None, it must be a dict that defines the
51
+ environment variables for the new process; these are used instead
52
+ of inheriting the current process environment, which is the default
53
+ behavior. (templated)
54
+ :param append_env: If False(default) uses the environment variables passed in env params
55
+ and does not inherit the current process environment. If True, inherits the environment variables
56
+ from current passes and then environment variable passed by the user will either update the existing
57
+ inherited environment variables or the new variables gets appended to it
58
+ :param output_encoding: Output encoding of Bash command
59
+ :param skip_on_exit_code: If task exits with this exit code, leave the task
60
+ in ``skipped`` state (default: 99). If set to ``None``, any non-zero
61
+ exit code will be treated as a failure.
62
+ :param cwd: Working directory to execute the command in (templated).
63
+ If None (default), the command is run in a temporary directory.
64
+ To use current DAG folder as the working directory,
65
+ you might set template ``{{ dag_run.dag.folder }}``.
66
+ :param output_processor: Function to further process the output of the bash script
67
+ (default is lambda output: output).
68
+
69
+ Airflow will evaluate the exit code of the Bash command. In general, a non-zero exit code will result in
70
+ task failure and zero will result in task success.
71
+ Exit code ``99`` (or another set in ``skip_on_exit_code``)
72
+ will throw an :class:`airflow.exceptions.AirflowSkipException`, which will leave the task in ``skipped``
73
+ state. You can have all non-zero exit codes be treated as a failure by setting ``skip_on_exit_code=None``.
74
+
75
+ .. list-table::
76
+ :widths: 25 25
77
+ :header-rows: 1
78
+
79
+ * - Exit code
80
+ - Behavior
81
+ * - 0
82
+ - success
83
+ * - `skip_on_exit_code` (default: 99)
84
+ - raise :class:`airflow.exceptions.AirflowSkipException`
85
+ * - otherwise
86
+ - raise :class:`airflow.exceptions.AirflowException`
87
+
88
+ .. note::
89
+
90
+ Airflow will not recognize a non-zero exit code unless the whole shell exit with a non-zero exit
91
+ code. This can be an issue if the non-zero exit arises from a sub-command. The easiest way of
92
+ addressing this is to prefix the command with ``set -e;``
93
+
94
+ .. code-block:: python
95
+
96
+ bash_command = "set -e; python3 script.py '{{ next_execution_date }}'"
97
+
98
+ .. note::
99
+
100
+ Add a space after the script name when directly calling a ``.sh`` script with the
101
+ ``bash_command`` argument -- for example ``bash_command="my_script.sh "``. This
102
+ is because Airflow tries to apply load this file and process it as a Jinja template to
103
+ it ends with ``.sh``, which will likely not be what most users want.
104
+
105
+ .. warning::
106
+
107
+ Care should be taken with "user" input or when using Jinja templates in the
108
+ ``bash_command``, as this bash operator does not perform any escaping or
109
+ sanitization of the command.
110
+
111
+ This applies mostly to using "dag_run" conf, as that can be submitted via
112
+ users in the Web UI. Most of the default template variables are not at
113
+ risk.
114
+
115
+ For example, do **not** do this:
116
+
117
+ .. code-block:: python
118
+
119
+ bash_task = BashOperator(
120
+ task_id="bash_task",
121
+ bash_command='echo "Here is the message: \'{{ dag_run.conf["message"] if dag_run else "" }}\'"',
122
+ )
123
+
124
+ Instead, you should pass this via the ``env`` kwarg and use double-quotes
125
+ inside the bash_command, as below:
126
+
127
+ .. code-block:: python
128
+
129
+ bash_task = BashOperator(
130
+ task_id="bash_task",
131
+ bash_command="echo \"here is the message: '$message'\"",
132
+ env={"message": '{{ dag_run.conf["message"] if dag_run else "" }}'},
133
+ )
134
+
135
+ .. versionadded:: 2.10.0
136
+ The `output_processor` parameter.
137
+
138
+ """
139
+
140
+ template_fields: Sequence[str] = ("bash_command", "env", "cwd")
141
+ template_fields_renderers = {"bash_command": "bash", "env": "json"}
142
+ template_ext: Sequence[str] = (".sh", ".bash")
143
+ ui_color = "#f0ede4"
144
+
145
+ def __init__(
146
+ self,
147
+ *,
148
+ bash_command: str | ArgNotSet,
149
+ env: dict[str, str] | None = None,
150
+ append_env: bool = False,
151
+ output_encoding: str = "utf-8",
152
+ skip_exit_code: int | None = None,
153
+ skip_on_exit_code: int | Container[int] | None = 99,
154
+ cwd: str | None = None,
155
+ output_processor: Callable[[str], Any] = lambda result: result,
156
+ **kwargs,
157
+ ) -> None:
158
+ super().__init__(**kwargs)
159
+ self.bash_command = bash_command
160
+ self.env = env
161
+ self.output_encoding = output_encoding
162
+ if skip_exit_code is not None:
163
+ warnings.warn(
164
+ "skip_exit_code is deprecated. Please use skip_on_exit_code", DeprecationWarning, stacklevel=2
165
+ )
166
+ skip_on_exit_code = skip_exit_code
167
+ self.skip_on_exit_code = (
168
+ skip_on_exit_code
169
+ if isinstance(skip_on_exit_code, Container)
170
+ else [skip_on_exit_code]
171
+ if skip_on_exit_code is not None
172
+ else []
173
+ )
174
+ self.cwd = cwd
175
+ self.append_env = append_env
176
+ self.output_processor = output_processor
177
+
178
+ # When using the @task.bash decorator, the Bash command is not known until the underlying Python
179
+ # callable is executed and therefore set to NOTSET initially. This flag is useful during execution to
180
+ # determine whether the bash_command value needs to re-rendered.
181
+ self._init_bash_command_not_set = isinstance(self.bash_command, ArgNotSet)
182
+
183
+ @cached_property
184
+ def subprocess_hook(self):
185
+ """Returns hook for running the bash command."""
186
+ return SubprocessHook()
187
+
188
+ @staticmethod
189
+ def refresh_bash_command(ti: TaskInstance) -> None:
190
+ """
191
+ Rewrite the underlying rendered bash_command value for a task instance in the metadatabase.
192
+
193
+ TaskInstance.get_rendered_template_fields() cannot be used because this will retrieve the
194
+ RenderedTaskInstanceFields from the metadatabase which doesn't have the runtime-evaluated bash_command
195
+ value.
196
+
197
+ :meta private:
198
+ """
199
+ from airflow.models.renderedtifields import RenderedTaskInstanceFields
200
+
201
+ RenderedTaskInstanceFields._update_runtime_evaluated_template_fields(ti)
202
+
203
+ def get_env(self, context):
204
+ """Build the set of environment variables to be exposed for the bash command."""
205
+ system_env = os.environ.copy()
206
+ env = self.env
207
+ if env is None:
208
+ env = system_env
209
+ else:
210
+ if self.append_env:
211
+ system_env.update(env)
212
+ env = system_env
213
+
214
+ airflow_context_vars = context_to_airflow_vars(context, in_env_var_format=True)
215
+ self.log.debug(
216
+ "Exporting env vars: %s",
217
+ " ".join(f"{k}={v!r}" for k, v in airflow_context_vars.items()),
218
+ )
219
+ env.update(airflow_context_vars)
220
+ return env
221
+
222
+ def execute(self, context: Context):
223
+ bash_path = shutil.which("bash") or "bash"
224
+ if self.cwd is not None:
225
+ if not os.path.exists(self.cwd):
226
+ raise AirflowException(f"Can not find the cwd: {self.cwd}")
227
+ if not os.path.isdir(self.cwd):
228
+ raise AirflowException(f"The cwd {self.cwd} must be a directory")
229
+ env = self.get_env(context)
230
+
231
+ # Because the bash_command value is evaluated at runtime using the @task.bash decorator, the
232
+ # RenderedTaskInstanceField data needs to be rewritten and the bash_command value re-rendered -- the
233
+ # latter because the returned command from the decorated callable could contain a Jinja expression.
234
+ # Both will ensure the correct Bash command is executed and that the Rendered Template view in the UI
235
+ # displays the executed command (otherwise it will display as an ArgNotSet type).
236
+ if self._init_bash_command_not_set:
237
+ ti = cast("TaskInstance", context["ti"])
238
+ self.refresh_bash_command(ti)
239
+
240
+ result = self.subprocess_hook.run_command(
241
+ command=[bash_path, "-c", self.bash_command],
242
+ env=env,
243
+ output_encoding=self.output_encoding,
244
+ cwd=self.cwd,
245
+ )
246
+ if result.exit_code in self.skip_on_exit_code:
247
+ raise AirflowSkipException(f"Bash command returned exit code {result.exit_code}. Skipping.")
248
+ elif result.exit_code != 0:
249
+ raise AirflowException(
250
+ f"Bash command failed. The command returned a non-zero exit code {result.exit_code}."
251
+ )
252
+
253
+ return self.output_processor(result.output)
254
+
255
+ def on_kill(self) -> None:
256
+ self.subprocess_hook.send_sigterm()
@@ -0,0 +1,114 @@
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
+
20
+ import os
21
+ from subprocess import PIPE, STDOUT, Popen
22
+ from tempfile import NamedTemporaryFile, TemporaryDirectory, gettempdir
23
+ from typing import TYPE_CHECKING, Sequence
24
+
25
+ from airflow.exceptions import AirflowFailException
26
+ from airflow.sensors.base import BaseSensorOperator
27
+
28
+ if TYPE_CHECKING:
29
+ from airflow.utils.context import Context
30
+
31
+
32
+ class BashSensor(BaseSensorOperator):
33
+ """
34
+ Executes a bash command/script.
35
+
36
+ Return True if and only if the return code is 0.
37
+
38
+ :param bash_command: The command, set of commands or reference to a
39
+ bash script (must be '.sh') to be executed.
40
+
41
+ :param env: If env is not None, it must be a mapping that defines the
42
+ environment variables for the new process; these are used instead
43
+ of inheriting the current process environment, which is the default
44
+ behavior. (templated)
45
+ :param output_encoding: output encoding of bash command.
46
+ :param retry_exit_code: If task exits with this code, treat the sensor
47
+ as not-yet-complete and retry the check later according to the
48
+ usual retry/timeout settings. Any other non-zero return code will
49
+ be treated as an error, and cause the sensor to fail. If set to
50
+ ``None`` (the default), any non-zero exit code will cause a retry
51
+ and the task will never raise an error except on time-out.
52
+
53
+ .. seealso::
54
+ For more information on how to use this sensor,take a look at the guide:
55
+ :ref:`howto/operator:BashSensor`
56
+ """
57
+
58
+ template_fields: Sequence[str] = ("bash_command", "env")
59
+
60
+ def __init__(
61
+ self, *, bash_command, env=None, output_encoding="utf-8", retry_exit_code: int | None = None, **kwargs
62
+ ):
63
+ super().__init__(**kwargs)
64
+ self.bash_command = bash_command
65
+ self.env = env
66
+ self.output_encoding = output_encoding
67
+ self.retry_exit_code = retry_exit_code
68
+
69
+ def poke(self, context: Context):
70
+ """Execute the bash command in a temporary directory."""
71
+ bash_command = self.bash_command
72
+ self.log.info("Tmp dir root location: %s", gettempdir())
73
+ with TemporaryDirectory(prefix="airflowtmp") as tmp_dir, NamedTemporaryFile(
74
+ dir=tmp_dir, prefix=self.task_id
75
+ ) as f:
76
+ f.write(bytes(bash_command, "utf_8"))
77
+ f.flush()
78
+ fname = f.name
79
+ script_location = tmp_dir + "/" + fname
80
+ self.log.info("Temporary script location: %s", script_location)
81
+ self.log.info("Running command: %s", bash_command)
82
+
83
+ with Popen(
84
+ ["bash", fname],
85
+ stdout=PIPE,
86
+ stderr=STDOUT,
87
+ close_fds=True,
88
+ cwd=tmp_dir,
89
+ env=self.env,
90
+ preexec_fn=os.setsid,
91
+ ) as resp:
92
+ if resp.stdout:
93
+ self.log.info("Output:")
94
+ for line in iter(resp.stdout.readline, b""):
95
+ self.log.info(line.decode(self.output_encoding).strip())
96
+ resp.wait()
97
+ self.log.info("Command exited with return code %s", resp.returncode)
98
+
99
+ # zero code means success, the sensor can go green
100
+ if resp.returncode == 0:
101
+ return True
102
+
103
+ # we have a retry exit code, sensor retries if return code matches, otherwise error
104
+ elif self.retry_exit_code is not None:
105
+ if resp.returncode == self.retry_exit_code:
106
+ self.log.info("Return code matches retry code, will retry later")
107
+ return False
108
+ else:
109
+ raise AirflowFailException(f"Command exited with return code {resp.returncode}")
110
+
111
+ # backwards compatibility: sensor retries no matter the error code
112
+ else:
113
+ self.log.info("Non-zero return code and no retry code set, will retry later")
114
+ return False
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: apache-airflow-providers-standard
3
- Version: 1.0.0.dev0
3
+ Version: 1.0.0.dev1
4
4
  Summary: Provider package apache-airflow-providers-standard for Apache Airflow
5
5
  Keywords: airflow-provider,standard,airflow,integration
6
6
  Author-email: Apache Software Foundation <dev@airflow.apache.org>
@@ -74,7 +74,7 @@ Project-URL: YouTube, https://www.youtube.com/channel/UCSXwxpWZQ7XZ1WL3wqevChA/
74
74
 
75
75
  Package ``apache-airflow-providers-standard``
76
76
 
77
- Release: ``1.0.0.dev0``
77
+ Release: ``1.0.0.dev1``
78
78
 
79
79
 
80
80
  Airflow Standard Provider
@@ -1,15 +1,17 @@
1
1
  airflow/providers/standard/LICENSE,sha256=FFb4jd2AXnOOf7XLP04pQW6jbdhG49TxlGY6fFpCV1Y,13609
2
2
  airflow/providers/standard/__init__.py,sha256=mlJxuZLkd5x-iq2SBwD3mvRQpt3YR7wjz_nceyF1IaI,787
3
- airflow/providers/standard/get_provider_info.py,sha256=YOJ5MXuFZYg9TBhXtStPLjwKRCXwBj5sT1N_QE64i6s,2431
3
+ airflow/providers/standard/get_provider_info.py,sha256=nFqgVL44xY7Xwa-Y2mn8SLMD-NH7lW_aNqgT17f0gLo,2559
4
4
  airflow/providers/standard/operators/__init__.py,sha256=9hdXHABrVpkbpjZgUft39kOFL2xSGeG4GEua0Hmelus,785
5
+ airflow/providers/standard/operators/bash.py,sha256=mxHM1Uc57Twh-OS1r3nCX7QKpatsBVb1PJVI3OEGJCk,10801
5
6
  airflow/providers/standard/operators/datetime.py,sha256=nk0gwO_H8vIIu8ztA4zryWqZeoSokfINTu4o2vPUcPc,4562
6
7
  airflow/providers/standard/operators/weekday.py,sha256=ws1FHHxFVEZhq8MDfBvNmI9pjH5QcHqueRkuanhayeQ,4474
7
8
  airflow/providers/standard/sensors/__init__.py,sha256=9hdXHABrVpkbpjZgUft39kOFL2xSGeG4GEua0Hmelus,785
9
+ airflow/providers/standard/sensors/bash.py,sha256=Gyi8zMwSESPyanlG9jbN9u-an6Vj33s7lTlmjWmjgSA,4821
8
10
  airflow/providers/standard/sensors/date_time.py,sha256=WKoMTLuSYwNbsvvkndRmiTGa6GN3jeolAGazbPDMeUk,5179
9
11
  airflow/providers/standard/sensors/time.py,sha256=nhKqn7eQKnx-F-MSG_yrlN7RM8ZM3iOSUwgqxc_F2SQ,4142
10
12
  airflow/providers/standard/sensors/time_delta.py,sha256=YMNELt0m89PvWsYmWWO-m6RW-ICPOZ8rcABrmt-4xxc,4660
11
13
  airflow/providers/standard/sensors/weekday.py,sha256=PMg0eoGuD0xNLSJIBY9C1Y0aqSZn6PkQ_j_eYo7lnks,3695
12
- apache_airflow_providers_standard-1.0.0.dev0.dist-info/entry_points.txt,sha256=mW2YRh3mVdZdaP5-iGSNgmcCh3YYdALIn28BCLBZZ40,104
13
- apache_airflow_providers_standard-1.0.0.dev0.dist-info/WHEEL,sha256=EZbGkh7Ie4PoZfRQ8I0ZuP9VklN_TvcZ6DSE5Uar4z4,81
14
- apache_airflow_providers_standard-1.0.0.dev0.dist-info/METADATA,sha256=unzipTVuHhQdPFzlb3VhMm9OXHFvX72zrRwrk9NUev0,4698
15
- apache_airflow_providers_standard-1.0.0.dev0.dist-info/RECORD,,
14
+ apache_airflow_providers_standard-1.0.0.dev1.dist-info/entry_points.txt,sha256=mW2YRh3mVdZdaP5-iGSNgmcCh3YYdALIn28BCLBZZ40,104
15
+ apache_airflow_providers_standard-1.0.0.dev1.dist-info/WHEEL,sha256=EZbGkh7Ie4PoZfRQ8I0ZuP9VklN_TvcZ6DSE5Uar4z4,81
16
+ apache_airflow_providers_standard-1.0.0.dev1.dist-info/METADATA,sha256=Q_aHdns_3O3-ukEP8lq8HJvSd9QZ0ENFnK-MSDOO_1g,4698
17
+ apache_airflow_providers_standard-1.0.0.dev1.dist-info/RECORD,,