apache-airflow-providers-standard 0.0.3rc2__py3-none-any.whl → 1.0.0.dev0__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.

Files changed (35) hide show
  1. airflow/providers/standard/__init__.py +1 -23
  2. airflow/providers/standard/get_provider_info.py +5 -52
  3. airflow/providers/standard/operators/datetime.py +2 -3
  4. airflow/providers/standard/operators/weekday.py +1 -4
  5. airflow/providers/standard/sensors/date_time.py +7 -27
  6. airflow/providers/standard/sensors/time.py +4 -23
  7. airflow/providers/standard/sensors/time_delta.py +4 -29
  8. airflow/providers/standard/sensors/weekday.py +1 -2
  9. {apache_airflow_providers_standard-0.0.3rc2.dist-info → apache_airflow_providers_standard-1.0.0.dev0.dist-info}/METADATA +17 -18
  10. apache_airflow_providers_standard-1.0.0.dev0.dist-info/RECORD +15 -0
  11. {apache_airflow_providers_standard-0.0.3rc2.dist-info → apache_airflow_providers_standard-1.0.0.dev0.dist-info}/WHEEL +1 -1
  12. airflow/providers/standard/hooks/__init__.py +0 -16
  13. airflow/providers/standard/hooks/filesystem.py +0 -89
  14. airflow/providers/standard/hooks/package_index.py +0 -95
  15. airflow/providers/standard/hooks/subprocess.py +0 -119
  16. airflow/providers/standard/operators/bash.py +0 -312
  17. airflow/providers/standard/operators/generic_transfer.py +0 -134
  18. airflow/providers/standard/operators/latest_only.py +0 -78
  19. airflow/providers/standard/operators/python.py +0 -1155
  20. airflow/providers/standard/operators/trigger_dagrun.py +0 -296
  21. airflow/providers/standard/sensors/bash.py +0 -116
  22. airflow/providers/standard/sensors/external_task.py +0 -512
  23. airflow/providers/standard/sensors/filesystem.py +0 -154
  24. airflow/providers/standard/sensors/python.py +0 -81
  25. airflow/providers/standard/triggers/__init__.py +0 -16
  26. airflow/providers/standard/triggers/external_task.py +0 -216
  27. airflow/providers/standard/triggers/file.py +0 -77
  28. airflow/providers/standard/triggers/temporal.py +0 -114
  29. airflow/providers/standard/utils/__init__.py +0 -16
  30. airflow/providers/standard/utils/python_virtualenv.py +0 -209
  31. airflow/providers/standard/utils/python_virtualenv_script.jinja2 +0 -101
  32. airflow/providers/standard/utils/sensor_helper.py +0 -123
  33. airflow/providers/standard/version_compat.py +0 -36
  34. apache_airflow_providers_standard-0.0.3rc2.dist-info/RECORD +0 -37
  35. {apache_airflow_providers_standard-0.0.3rc2.dist-info → apache_airflow_providers_standard-1.0.0.dev0.dist-info}/entry_points.txt +0 -0
@@ -1,95 +0,0 @@
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
- """Hook for additional Package Indexes (Python)."""
19
-
20
- from __future__ import annotations
21
-
22
- import subprocess
23
- from typing import Any
24
- from urllib.parse import quote, urlparse
25
-
26
- from airflow.hooks.base import BaseHook
27
-
28
-
29
- class PackageIndexHook(BaseHook):
30
- """Specify package indexes/Python package sources using Airflow connections."""
31
-
32
- conn_name_attr = "pi_conn_id"
33
- default_conn_name = "package_index_default"
34
- conn_type = "package_index"
35
- hook_name = "Package Index (Python)"
36
-
37
- def __init__(self, pi_conn_id: str = default_conn_name, **kwargs) -> None:
38
- super().__init__(**kwargs)
39
- self.pi_conn_id = pi_conn_id
40
- self.conn = None
41
-
42
- @staticmethod
43
- def get_ui_field_behaviour() -> dict[str, Any]:
44
- """Return custom field behaviour."""
45
- return {
46
- "hidden_fields": ["schema", "port", "extra"],
47
- "relabeling": {"host": "Package Index URL"},
48
- "placeholders": {
49
- "host": "Example: https://my-package-mirror.net/pypi/repo-name/simple",
50
- "login": "Username for package index",
51
- "password": "Password for package index (will be masked)",
52
- },
53
- }
54
-
55
- @staticmethod
56
- def _get_basic_auth_conn_url(index_url: str, user: str | None, password: str | None) -> str:
57
- """Return a connection URL with basic auth credentials based on connection config."""
58
- url = urlparse(index_url)
59
- host = url.netloc.split("@")[-1]
60
- if user:
61
- if password:
62
- host = f"{quote(user)}:{quote(password)}@{host}"
63
- else:
64
- host = f"{quote(user)}@{host}"
65
- return url._replace(netloc=host).geturl()
66
-
67
- def get_conn(self) -> Any:
68
- """Return connection for the hook."""
69
- return self.get_connection_url()
70
-
71
- def get_connection_url(self) -> Any:
72
- """Return a connection URL with embedded credentials."""
73
- conn = self.get_connection(self.pi_conn_id)
74
- index_url = conn.host
75
- if not index_url:
76
- raise ValueError("Please provide an index URL.")
77
- return self._get_basic_auth_conn_url(index_url, conn.login, conn.password)
78
-
79
- def test_connection(self) -> tuple[bool, str]:
80
- """Test connection to package index url."""
81
- conn_url = self.get_connection_url()
82
- proc = subprocess.run(
83
- ["pip", "search", "not-existing-test-package", "--no-input", "--index", conn_url],
84
- check=False,
85
- capture_output=True,
86
- )
87
- conn = self.get_connection(self.pi_conn_id)
88
- if proc.returncode not in [
89
- 0, # executed successfully, found package
90
- 23, # executed successfully, didn't find any packages
91
- # (but we do not expect it to find 'not-existing-test-package')
92
- ]:
93
- return False, f"Connection test to {conn.host} failed. Error: {str(proc.stderr)}"
94
-
95
- return True, f"Connection to {conn.host} tested successfully!"
@@ -1,119 +0,0 @@
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
-
19
- import contextlib
20
- import os
21
- import signal
22
- from collections import namedtuple
23
- from collections.abc import Iterator
24
- from subprocess import PIPE, STDOUT, Popen
25
- from tempfile import TemporaryDirectory, gettempdir
26
-
27
- from airflow.hooks.base import BaseHook
28
-
29
- SubprocessResult = namedtuple("SubprocessResult", ["exit_code", "output"])
30
-
31
-
32
- @contextlib.contextmanager
33
- def working_directory(cwd: str | None = None) -> Iterator[str]:
34
- """
35
- Context manager for handling (temporary) working directory.
36
-
37
- Use the given cwd as working directory, if provided.
38
- Otherwise, create a temporary directory.
39
- """
40
- with contextlib.ExitStack() as stack:
41
- if cwd is None:
42
- cwd = stack.enter_context(TemporaryDirectory(prefix="airflowtmp"))
43
- yield cwd
44
-
45
-
46
- class SubprocessHook(BaseHook):
47
- """Hook for running processes with the ``subprocess`` module."""
48
-
49
- def __init__(self, **kwargs) -> None:
50
- self.sub_process: Popen[bytes] | None = None
51
- super().__init__(**kwargs)
52
-
53
- def run_command(
54
- self,
55
- command: list[str],
56
- env: dict[str, str] | None = None,
57
- output_encoding: str = "utf-8",
58
- cwd: str | None = None,
59
- ) -> SubprocessResult:
60
- """
61
- Execute the command.
62
-
63
- If ``cwd`` is None, execute the command in a temporary directory which will be cleaned afterwards.
64
- If ``env`` is not supplied, ``os.environ`` is passed
65
-
66
- :param command: the command to run
67
- :param env: Optional dict containing environment variables to be made available to the shell
68
- environment in which ``command`` will be executed. If omitted, ``os.environ`` will be used.
69
- Note, that in case you have Sentry configured, original variables from the environment
70
- will also be passed to the subprocess with ``SUBPROCESS_`` prefix. See:
71
- https://airflow.apache.org/docs/apache-airflow/stable/administration-and-deployment/logging-monitoring/errors.html for details.
72
- :param output_encoding: encoding to use for decoding stdout
73
- :param cwd: Working directory to run the command in.
74
- If None (default), the command is run in a temporary directory.
75
- :return: :class:`namedtuple` containing ``exit_code`` and ``output``, the last line from stderr
76
- or stdout
77
- """
78
- self.log.info("Tmp dir root location: %s", gettempdir())
79
- with working_directory(cwd=cwd) as cwd:
80
-
81
- def pre_exec():
82
- # Restore default signal disposition and invoke setsid
83
- for sig in ("SIGPIPE", "SIGXFZ", "SIGXFSZ"):
84
- if hasattr(signal, sig):
85
- signal.signal(getattr(signal, sig), signal.SIG_DFL)
86
- os.setsid()
87
-
88
- self.log.info("Running command: %s", command)
89
-
90
- self.sub_process = Popen(
91
- command,
92
- stdout=PIPE,
93
- stderr=STDOUT,
94
- cwd=cwd,
95
- env=env if env or env == {} else os.environ,
96
- preexec_fn=pre_exec,
97
- )
98
-
99
- self.log.info("Output:")
100
- line = ""
101
- if self.sub_process is None:
102
- raise RuntimeError("The subprocess should be created here and is None!")
103
- if self.sub_process.stdout is not None:
104
- for raw_line in iter(self.sub_process.stdout.readline, b""):
105
- line = raw_line.decode(output_encoding, errors="backslashreplace").rstrip()
106
- self.log.info("%s", line)
107
-
108
- self.sub_process.wait()
109
-
110
- self.log.info("Command exited with return code %s", self.sub_process.returncode)
111
- return_code: int = self.sub_process.returncode
112
-
113
- return SubprocessResult(exit_code=return_code, output=line)
114
-
115
- def send_sigterm(self):
116
- """Send SIGTERM signal to ``self.sub_process`` if one exists."""
117
- self.log.info("Sending SIGTERM signal to process group")
118
- if self.sub_process and hasattr(self.sub_process, "pid"):
119
- os.killpg(os.getpgid(self.sub_process.pid), signal.SIGTERM)
@@ -1,312 +0,0 @@
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 tempfile
23
- from collections.abc import Container, Sequence
24
- from functools import cached_property
25
- from typing import TYPE_CHECKING, Any, Callable, cast
26
-
27
- from airflow.exceptions import AirflowException, AirflowSkipException
28
- from airflow.models.baseoperator import BaseOperator
29
- from airflow.providers.standard.hooks.subprocess import SubprocessHook, SubprocessResult, working_directory
30
- from airflow.utils.operator_helpers import context_to_airflow_vars
31
- from airflow.utils.session import NEW_SESSION, provide_session
32
- from airflow.utils.types import ArgNotSet
33
-
34
- if TYPE_CHECKING:
35
- from sqlalchemy.orm import Session as SASession
36
-
37
- from airflow.models.taskinstance import TaskInstance
38
- from airflow.utils.context import Context
39
-
40
-
41
- class BashOperator(BaseOperator):
42
- r"""
43
- Execute a Bash script, command or set of commands.
44
-
45
- .. seealso::
46
- For more information on how to use this operator, take a look at the guide:
47
- :ref:`howto/operator:BashOperator`
48
-
49
- If BaseOperator.do_xcom_push is True, the last line written to stdout
50
- will also be pushed to an XCom when the bash command completes
51
-
52
- :param bash_command: The command, set of commands or reference to a
53
- Bash script (must be '.sh' or '.bash') to be executed. (templated)
54
- :param env: If env is not None, it must be a dict that defines the
55
- environment variables for the new process; these are used instead
56
- of inheriting the current process environment, which is the default
57
- behavior. (templated)
58
- :param append_env: If False(default) uses the environment variables passed in env params
59
- and does not inherit the current process environment. If True, inherits the environment variables
60
- from current passes and then environment variable passed by the user will either update the existing
61
- inherited environment variables or the new variables gets appended to it
62
- :param output_encoding: Output encoding of Bash command
63
- :param skip_on_exit_code: If task exits with this exit code, leave the task
64
- in ``skipped`` state (default: 99). If set to ``None``, any non-zero
65
- exit code will be treated as a failure.
66
- :param cwd: Working directory to execute the command in (templated).
67
- If None (default), the command is run in a temporary directory.
68
- To use current DAG folder as the working directory,
69
- you might set template ``{{ dag_run.dag.folder }}``.
70
- When bash_command is a '.sh' or '.bash' file, Airflow must have write
71
- access to the working directory. The script will be rendered (Jinja
72
- template) into a new temporary file in this directory.
73
- :param output_processor: Function to further process the output of the bash script
74
- (default is lambda output: output).
75
-
76
- Airflow will evaluate the exit code of the Bash command. In general, a non-zero exit code will result in
77
- task failure and zero will result in task success.
78
- Exit code ``99`` (or another set in ``skip_on_exit_code``)
79
- will throw an :class:`airflow.exceptions.AirflowSkipException`, which will leave the task in ``skipped``
80
- state. You can have all non-zero exit codes be treated as a failure by setting ``skip_on_exit_code=None``.
81
-
82
- .. list-table::
83
- :widths: 25 25
84
- :header-rows: 1
85
-
86
- * - Exit code
87
- - Behavior
88
- * - 0
89
- - success
90
- * - `skip_on_exit_code` (default: 99)
91
- - raise :class:`airflow.exceptions.AirflowSkipException`
92
- * - otherwise
93
- - raise :class:`airflow.exceptions.AirflowException`
94
-
95
- .. note::
96
-
97
- Airflow will not recognize a non-zero exit code unless the whole shell exit with a non-zero exit
98
- code. This can be an issue if the non-zero exit arises from a sub-command. The easiest way of
99
- addressing this is to prefix the command with ``set -e;``
100
-
101
- .. code-block:: python
102
-
103
- bash_command = "set -e; python3 script.py '{{ data_interval_end }}'"
104
-
105
- .. note::
106
-
107
- To simply execute a ``.sh`` or ``.bash`` script (without any Jinja template), add a space after the
108
- script name ``bash_command`` argument -- for example ``bash_command="my_script.sh "``. This
109
- is because Airflow tries to load this file and process it as a Jinja template when
110
- it ends with ``.sh`` or ``.bash``.
111
-
112
- If you have Jinja template in your script, do not put any blank space. And add the script's directory
113
- in the DAG's ``template_searchpath``. If you specify a ``cwd``, Airflow must have write access to
114
- this directory. The script will be rendered (Jinja template) into a new temporary file in this directory.
115
-
116
- .. warning::
117
-
118
- Care should be taken with "user" input or when using Jinja templates in the
119
- ``bash_command``, as this bash operator does not perform any escaping or
120
- sanitization of the command.
121
-
122
- This applies mostly to using "dag_run" conf, as that can be submitted via
123
- users in the Web UI. Most of the default template variables are not at
124
- risk.
125
-
126
- For example, do **not** do this:
127
-
128
- .. code-block:: python
129
-
130
- bash_task = BashOperator(
131
- task_id="bash_task",
132
- bash_command='echo "Here is the message: \'{{ dag_run.conf["message"] if dag_run else "" }}\'"',
133
- )
134
-
135
- Instead, you should pass this via the ``env`` kwarg and use double-quotes
136
- inside the bash_command, as below:
137
-
138
- .. code-block:: python
139
-
140
- bash_task = BashOperator(
141
- task_id="bash_task",
142
- bash_command="echo \"here is the message: '$message'\"",
143
- env={"message": '{{ dag_run.conf["message"] if dag_run else "" }}'},
144
- )
145
-
146
- .. versionadded:: 2.10.0
147
- The `output_processor` parameter.
148
-
149
- """
150
-
151
- template_fields: Sequence[str] = ("bash_command", "env", "cwd")
152
- template_fields_renderers = {"bash_command": "bash", "env": "json"}
153
- template_ext: Sequence[str] = (".sh", ".bash")
154
- ui_color = "#f0ede4"
155
-
156
- def __init__(
157
- self,
158
- *,
159
- bash_command: str | ArgNotSet,
160
- env: dict[str, str] | None = None,
161
- append_env: bool = False,
162
- output_encoding: str = "utf-8",
163
- skip_on_exit_code: int | Container[int] | None = 99,
164
- cwd: str | None = None,
165
- output_processor: Callable[[str], Any] = lambda result: result,
166
- **kwargs,
167
- ) -> None:
168
- super().__init__(**kwargs)
169
- self.bash_command = bash_command
170
- self.env = env
171
- self.output_encoding = output_encoding
172
- self.skip_on_exit_code = (
173
- skip_on_exit_code
174
- if isinstance(skip_on_exit_code, Container)
175
- else [skip_on_exit_code]
176
- if skip_on_exit_code is not None
177
- else []
178
- )
179
- self.cwd = cwd
180
- self.append_env = append_env
181
- self.output_processor = output_processor
182
-
183
- # When using the @task.bash decorator, the Bash command is not known until the underlying Python
184
- # callable is executed and therefore set to NOTSET initially. This flag is useful during execution to
185
- # determine whether the bash_command value needs to re-rendered.
186
- self._init_bash_command_not_set = isinstance(self.bash_command, ArgNotSet)
187
-
188
- # Keep a copy of the original bash_command, without the Jinja template rendered.
189
- # This is later used to determine if the bash_command is a script or an inline string command.
190
- # We do this later, because the bash_command is not available in __init__ when using @task.bash.
191
- self._unrendered_bash_command: str | ArgNotSet = bash_command
192
-
193
- @cached_property
194
- def subprocess_hook(self):
195
- """Returns hook for running the bash command."""
196
- return SubprocessHook()
197
-
198
- # TODO: This should be replaced with Task SDK API call
199
- @staticmethod
200
- @provide_session
201
- def refresh_bash_command(ti: TaskInstance, session: SASession = NEW_SESSION) -> None:
202
- """
203
- Rewrite the underlying rendered bash_command value for a task instance in the metadatabase.
204
-
205
- TaskInstance.get_rendered_template_fields() cannot be used because this will retrieve the
206
- RenderedTaskInstanceFields from the metadatabase which doesn't have the runtime-evaluated bash_command
207
- value.
208
-
209
- :meta private:
210
- """
211
- from airflow.models.renderedtifields import RenderedTaskInstanceFields
212
-
213
- """Update rendered task instance fields for cases where runtime evaluated, not templated."""
214
- # Note: Need lazy import to break the partly loaded class loop
215
- from airflow.models.taskinstance import TaskInstance
216
-
217
- # If called via remote API the DAG needs to be re-loaded
218
- TaskInstance.ensure_dag(ti, session=session)
219
-
220
- rtif = RenderedTaskInstanceFields(ti)
221
- RenderedTaskInstanceFields.write(rtif, session=session)
222
- RenderedTaskInstanceFields.delete_old_records(ti.task_id, ti.dag_id, session=session)
223
-
224
- def get_env(self, context) -> dict:
225
- """Build the set of environment variables to be exposed for the bash command."""
226
- system_env = os.environ.copy()
227
- env = self.env
228
- if env is None:
229
- env = system_env
230
- else:
231
- if self.append_env:
232
- system_env.update(env)
233
- env = system_env
234
-
235
- airflow_context_vars = context_to_airflow_vars(context, in_env_var_format=True)
236
- self.log.debug(
237
- "Exporting env vars: %s",
238
- " ".join(f"{k}={v!r}" for k, v in airflow_context_vars.items()),
239
- )
240
- env.update(airflow_context_vars)
241
- return env
242
-
243
- def execute(self, context: Context):
244
- bash_path: str = shutil.which("bash") or "bash"
245
- if self.cwd is not None:
246
- if not os.path.exists(self.cwd):
247
- raise AirflowException(f"Can not find the cwd: {self.cwd}")
248
- if not os.path.isdir(self.cwd):
249
- raise AirflowException(f"The cwd {self.cwd} must be a directory")
250
- env = self.get_env(context)
251
-
252
- # Because the bash_command value is evaluated at runtime using the @task.bash decorator, the
253
- # RenderedTaskInstanceField data needs to be rewritten and the bash_command value re-rendered -- the
254
- # latter because the returned command from the decorated callable could contain a Jinja expression.
255
- # Both will ensure the correct Bash command is executed and that the Rendered Template view in the UI
256
- # displays the executed command (otherwise it will display as an ArgNotSet type).
257
- if self._init_bash_command_not_set:
258
- is_inline_command = self._is_inline_command(bash_command=cast(str, self.bash_command))
259
- ti = context["ti"]
260
- self.refresh_bash_command(ti)
261
- else:
262
- is_inline_command = self._is_inline_command(bash_command=cast(str, self._unrendered_bash_command))
263
-
264
- if is_inline_command:
265
- result = self._run_inline_command(bash_path=bash_path, env=env)
266
- else:
267
- result = self._run_rendered_script_file(bash_path=bash_path, env=env)
268
-
269
- if result.exit_code in self.skip_on_exit_code:
270
- raise AirflowSkipException(f"Bash command returned exit code {result.exit_code}. Skipping.")
271
- elif result.exit_code != 0:
272
- raise AirflowException(
273
- f"Bash command failed. The command returned a non-zero exit code {result.exit_code}."
274
- )
275
-
276
- return self.output_processor(result.output)
277
-
278
- def _run_inline_command(self, bash_path: str, env: dict) -> SubprocessResult:
279
- """Pass the bash command as string directly in the subprocess."""
280
- return self.subprocess_hook.run_command(
281
- command=[bash_path, "-c", self.bash_command],
282
- env=env,
283
- output_encoding=self.output_encoding,
284
- cwd=self.cwd,
285
- )
286
-
287
- def _run_rendered_script_file(self, bash_path: str, env: dict) -> SubprocessResult:
288
- """
289
- Save the bash command into a file and execute this file.
290
-
291
- This allows for longer commands, and prevents "Argument list too long error".
292
- """
293
- with working_directory(cwd=self.cwd) as cwd:
294
- with tempfile.NamedTemporaryFile(mode="w", dir=cwd, suffix=".sh") as file:
295
- file.write(cast(str, self.bash_command))
296
- file.flush()
297
-
298
- bash_script = os.path.basename(file.name)
299
- return self.subprocess_hook.run_command(
300
- command=[bash_path, bash_script],
301
- env=env,
302
- output_encoding=self.output_encoding,
303
- cwd=cwd,
304
- )
305
-
306
- @classmethod
307
- def _is_inline_command(cls, bash_command: str) -> bool:
308
- """Return True if the bash command is an inline string. False if it's a bash script file."""
309
- return not bash_command.endswith(tuple(cls.template_ext))
310
-
311
- def on_kill(self) -> None:
312
- self.subprocess_hook.send_sigterm()
@@ -1,134 +0,0 @@
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
- from collections.abc import Sequence
21
- from typing import TYPE_CHECKING
22
-
23
- from airflow.hooks.base import BaseHook
24
- from airflow.models import BaseOperator
25
-
26
- if TYPE_CHECKING:
27
- from airflow.utils.context import Context
28
-
29
-
30
- class GenericTransfer(BaseOperator):
31
- """
32
- Moves data from a connection to another.
33
-
34
- Assuming that they both provide the required methods in their respective hooks.
35
- The source hook needs to expose a `get_records` method, and the destination a
36
- `insert_rows` method.
37
-
38
- This is meant to be used on small-ish datasets that fit in memory.
39
-
40
- :param sql: SQL query to execute against the source database. (templated)
41
- :param destination_table: target table. (templated)
42
- :param source_conn_id: source connection. (templated)
43
- :param destination_conn_id: destination connection. (templated)
44
- :param preoperator: sql statement or list of statements to be
45
- executed prior to loading the data. (templated)
46
- :param insert_args: extra params for `insert_rows` method.
47
- """
48
-
49
- template_fields: Sequence[str] = (
50
- "source_conn_id",
51
- "destination_conn_id",
52
- "sql",
53
- "destination_table",
54
- "preoperator",
55
- "insert_args",
56
- )
57
- template_ext: Sequence[str] = (
58
- ".sql",
59
- ".hql",
60
- )
61
- template_fields_renderers = {"preoperator": "sql"}
62
- ui_color = "#b0f07c"
63
-
64
- def __init__(
65
- self,
66
- *,
67
- sql: str,
68
- destination_table: str,
69
- source_conn_id: str,
70
- source_hook_params: dict | None = None,
71
- destination_conn_id: str,
72
- destination_hook_params: dict | None = None,
73
- preoperator: str | list[str] | None = None,
74
- insert_args: dict | None = None,
75
- **kwargs,
76
- ) -> None:
77
- super().__init__(**kwargs)
78
- self.sql = sql
79
- self.destination_table = destination_table
80
- self.source_conn_id = source_conn_id
81
- self.source_hook_params = source_hook_params
82
- self.destination_conn_id = destination_conn_id
83
- self.destination_hook_params = destination_hook_params
84
- self.preoperator = preoperator
85
- self.insert_args = insert_args or {}
86
-
87
- @classmethod
88
- def get_hook(cls, conn_id: str, hook_params: dict | None = None) -> BaseHook:
89
- """
90
- Return default hook for this connection id.
91
-
92
- :param conn_id: connection id
93
- :param hook_params: hook parameters
94
- :return: default hook for this connection
95
- """
96
- connection = BaseHook.get_connection(conn_id)
97
- return connection.get_hook(hook_params=hook_params)
98
-
99
- def execute(self, context: Context):
100
- source_hook = self.get_hook(conn_id=self.source_conn_id, hook_params=self.source_hook_params)
101
- destination_hook = self.get_hook(
102
- conn_id=self.destination_conn_id, hook_params=self.destination_hook_params
103
- )
104
-
105
- self.log.info("Extracting data from %s", self.source_conn_id)
106
- self.log.info("Executing: \n %s", self.sql)
107
- get_records = getattr(source_hook, "get_records", None)
108
- if not callable(get_records):
109
- raise RuntimeError(
110
- f"Hook for connection {self.source_conn_id!r} "
111
- f"({type(source_hook).__name__}) has no `get_records` method"
112
- )
113
- else:
114
- results = get_records(self.sql)
115
-
116
- if self.preoperator:
117
- run = getattr(destination_hook, "run", None)
118
- if not callable(run):
119
- raise RuntimeError(
120
- f"Hook for connection {self.destination_conn_id!r} "
121
- f"({type(destination_hook).__name__}) has no `run` method"
122
- )
123
- self.log.info("Running preoperator")
124
- self.log.info(self.preoperator)
125
- run(self.preoperator)
126
-
127
- insert_rows = getattr(destination_hook, "insert_rows", None)
128
- if not callable(insert_rows):
129
- raise RuntimeError(
130
- f"Hook for connection {self.destination_conn_id!r} "
131
- f"({type(destination_hook).__name__}) has no `insert_rows` method"
132
- )
133
- self.log.info("Inserting rows into %s", self.destination_conn_id)
134
- insert_rows(table=self.destination_table, rows=results, **self.insert_args)