apache-airflow-providers-standard 0.1.0rc1__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.
- airflow/providers/standard/LICENSE +52 -0
- airflow/providers/standard/__init__.py +1 -23
- airflow/providers/standard/get_provider_info.py +7 -54
- airflow/providers/standard/operators/datetime.py +3 -8
- airflow/providers/standard/operators/weekday.py +4 -11
- airflow/providers/standard/sensors/date_time.py +8 -32
- airflow/providers/standard/sensors/time.py +5 -28
- airflow/providers/standard/sensors/time_delta.py +10 -48
- airflow/providers/standard/sensors/weekday.py +2 -7
- {apache_airflow_providers_standard-0.1.0rc1.dist-info → apache_airflow_providers_standard-1.0.0.dev0.dist-info}/METADATA +36 -20
- apache_airflow_providers_standard-1.0.0.dev0.dist-info/RECORD +15 -0
- {apache_airflow_providers_standard-0.1.0rc1.dist-info → apache_airflow_providers_standard-1.0.0.dev0.dist-info}/WHEEL +1 -1
- airflow/providers/standard/hooks/__init__.py +0 -16
- airflow/providers/standard/hooks/filesystem.py +0 -89
- airflow/providers/standard/hooks/package_index.py +0 -95
- airflow/providers/standard/hooks/subprocess.py +0 -119
- airflow/providers/standard/operators/bash.py +0 -310
- airflow/providers/standard/operators/empty.py +0 -39
- airflow/providers/standard/operators/generic_transfer.py +0 -138
- airflow/providers/standard/operators/latest_only.py +0 -83
- airflow/providers/standard/operators/python.py +0 -1132
- airflow/providers/standard/operators/trigger_dagrun.py +0 -292
- airflow/providers/standard/sensors/bash.py +0 -120
- airflow/providers/standard/sensors/external_task.py +0 -509
- airflow/providers/standard/sensors/filesystem.py +0 -158
- airflow/providers/standard/sensors/python.py +0 -85
- airflow/providers/standard/triggers/__init__.py +0 -16
- airflow/providers/standard/triggers/external_task.py +0 -211
- airflow/providers/standard/triggers/file.py +0 -131
- airflow/providers/standard/triggers/temporal.py +0 -114
- airflow/providers/standard/utils/__init__.py +0 -16
- airflow/providers/standard/utils/python_virtualenv.py +0 -209
- airflow/providers/standard/utils/python_virtualenv_script.jinja2 +0 -77
- airflow/providers/standard/utils/sensor_helper.py +0 -119
- airflow/providers/standard/version_compat.py +0 -36
- apache_airflow_providers_standard-0.1.0rc1.dist-info/RECORD +0 -38
- {apache_airflow_providers_standard-0.1.0rc1.dist-info → apache_airflow_providers_standard-1.0.0.dev0.dist-info}/entry_points.txt +0 -0
|
@@ -1,16 +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.
|
|
@@ -1,89 +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 pathlib import Path
|
|
21
|
-
from typing import Any
|
|
22
|
-
|
|
23
|
-
from airflow.hooks.base import BaseHook
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
class FSHook(BaseHook):
|
|
27
|
-
"""
|
|
28
|
-
Allows for interaction with an file server.
|
|
29
|
-
|
|
30
|
-
Connection should have a name and a path specified under extra:
|
|
31
|
-
|
|
32
|
-
example:
|
|
33
|
-
Connection Id: fs_test
|
|
34
|
-
Connection Type: File (path)
|
|
35
|
-
Host, Schema, Login, Password, Port: empty
|
|
36
|
-
Extra: {"path": "/tmp"}
|
|
37
|
-
"""
|
|
38
|
-
|
|
39
|
-
conn_name_attr = "fs_conn_id"
|
|
40
|
-
default_conn_name = "fs_default"
|
|
41
|
-
conn_type = "fs"
|
|
42
|
-
hook_name = "File (path)"
|
|
43
|
-
|
|
44
|
-
@classmethod
|
|
45
|
-
def get_connection_form_widgets(cls) -> dict[str, Any]:
|
|
46
|
-
"""Return connection widgets to add to connection form."""
|
|
47
|
-
from flask_appbuilder.fieldwidgets import BS3TextFieldWidget
|
|
48
|
-
from flask_babel import lazy_gettext
|
|
49
|
-
from wtforms import StringField
|
|
50
|
-
|
|
51
|
-
return {"path": StringField(lazy_gettext("Path"), widget=BS3TextFieldWidget())}
|
|
52
|
-
|
|
53
|
-
@classmethod
|
|
54
|
-
def get_ui_field_behaviour(cls) -> dict[str, Any]:
|
|
55
|
-
"""Return custom field behaviour."""
|
|
56
|
-
return {
|
|
57
|
-
"hidden_fields": ["host", "schema", "port", "login", "password", "extra"],
|
|
58
|
-
"relabeling": {},
|
|
59
|
-
"placeholders": {},
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
def __init__(self, fs_conn_id: str = default_conn_name, **kwargs):
|
|
63
|
-
super().__init__(**kwargs)
|
|
64
|
-
conn = self.get_connection(fs_conn_id)
|
|
65
|
-
self.basepath = conn.extra_dejson.get("path", "")
|
|
66
|
-
self.conn = conn
|
|
67
|
-
|
|
68
|
-
def get_conn(self) -> None:
|
|
69
|
-
pass
|
|
70
|
-
|
|
71
|
-
def get_path(self) -> str:
|
|
72
|
-
"""
|
|
73
|
-
Get the path to the filesystem location.
|
|
74
|
-
|
|
75
|
-
:return: the path.
|
|
76
|
-
"""
|
|
77
|
-
return self.basepath
|
|
78
|
-
|
|
79
|
-
def test_connection(self):
|
|
80
|
-
"""Test File connection."""
|
|
81
|
-
try:
|
|
82
|
-
p = self.get_path()
|
|
83
|
-
if not p:
|
|
84
|
-
return False, "File Path is undefined."
|
|
85
|
-
if not Path(p).exists():
|
|
86
|
-
return False, f"Path {p} does not exist."
|
|
87
|
-
return True, f"Path {p} is existing."
|
|
88
|
-
except Exception as e:
|
|
89
|
-
return False, str(e)
|
|
@@ -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,310 +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
|
-
try:
|
|
38
|
-
from airflow.sdk.definitions.context import Context
|
|
39
|
-
except ImportError:
|
|
40
|
-
# TODO: Remove once provider drops support for Airflow 2
|
|
41
|
-
from airflow.utils.context import Context
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
class BashOperator(BaseOperator):
|
|
45
|
-
r"""
|
|
46
|
-
Execute a Bash script, command or set of commands.
|
|
47
|
-
|
|
48
|
-
.. seealso::
|
|
49
|
-
For more information on how to use this operator, take a look at the guide:
|
|
50
|
-
:ref:`howto/operator:BashOperator`
|
|
51
|
-
|
|
52
|
-
If BaseOperator.do_xcom_push is True, the last line written to stdout
|
|
53
|
-
will also be pushed to an XCom when the bash command completes
|
|
54
|
-
|
|
55
|
-
:param bash_command: The command, set of commands or reference to a
|
|
56
|
-
Bash script (must be '.sh' or '.bash') to be executed. (templated)
|
|
57
|
-
:param env: If env is not None, it must be a dict that defines the
|
|
58
|
-
environment variables for the new process; these are used instead
|
|
59
|
-
of inheriting the current process environment, which is the default
|
|
60
|
-
behavior. (templated)
|
|
61
|
-
:param append_env: If False(default) uses the environment variables passed in env params
|
|
62
|
-
and does not inherit the current process environment. If True, inherits the environment variables
|
|
63
|
-
from current passes and then environment variable passed by the user will either update the existing
|
|
64
|
-
inherited environment variables or the new variables gets appended to it
|
|
65
|
-
:param output_encoding: Output encoding of Bash command
|
|
66
|
-
:param skip_on_exit_code: If task exits with this exit code, leave the task
|
|
67
|
-
in ``skipped`` state (default: 99). If set to ``None``, any non-zero
|
|
68
|
-
exit code will be treated as a failure.
|
|
69
|
-
:param cwd: Working directory to execute the command in (templated).
|
|
70
|
-
If None (default), the command is run in a temporary directory.
|
|
71
|
-
To use current DAG folder as the working directory,
|
|
72
|
-
you might set template ``{{ task.dag.folder }}``.
|
|
73
|
-
When bash_command is a '.sh' or '.bash' file, Airflow must have write
|
|
74
|
-
access to the working directory. The script will be rendered (Jinja
|
|
75
|
-
template) into a new temporary file in this directory.
|
|
76
|
-
:param output_processor: Function to further process the output of the bash script
|
|
77
|
-
(default is lambda output: output).
|
|
78
|
-
|
|
79
|
-
Airflow will evaluate the exit code of the Bash command. In general, a non-zero exit code will result in
|
|
80
|
-
task failure and zero will result in task success.
|
|
81
|
-
Exit code ``99`` (or another set in ``skip_on_exit_code``)
|
|
82
|
-
will throw an :class:`airflow.exceptions.AirflowSkipException`, which will leave the task in ``skipped``
|
|
83
|
-
state. You can have all non-zero exit codes be treated as a failure by setting ``skip_on_exit_code=None``.
|
|
84
|
-
|
|
85
|
-
.. list-table::
|
|
86
|
-
:widths: 25 25
|
|
87
|
-
:header-rows: 1
|
|
88
|
-
|
|
89
|
-
* - Exit code
|
|
90
|
-
- Behavior
|
|
91
|
-
* - 0
|
|
92
|
-
- success
|
|
93
|
-
* - `skip_on_exit_code` (default: 99)
|
|
94
|
-
- raise :class:`airflow.exceptions.AirflowSkipException`
|
|
95
|
-
* - otherwise
|
|
96
|
-
- raise :class:`airflow.exceptions.AirflowException`
|
|
97
|
-
|
|
98
|
-
.. note::
|
|
99
|
-
|
|
100
|
-
Airflow will not recognize a non-zero exit code unless the whole shell exit with a non-zero exit
|
|
101
|
-
code. This can be an issue if the non-zero exit arises from a sub-command. The easiest way of
|
|
102
|
-
addressing this is to prefix the command with ``set -e;``
|
|
103
|
-
|
|
104
|
-
.. code-block:: python
|
|
105
|
-
|
|
106
|
-
bash_command = "set -e; python3 script.py '{{ data_interval_end }}'"
|
|
107
|
-
|
|
108
|
-
.. note::
|
|
109
|
-
|
|
110
|
-
To simply execute a ``.sh`` or ``.bash`` script (without any Jinja template), add a space after the
|
|
111
|
-
script name ``bash_command`` argument -- for example ``bash_command="my_script.sh "``. This
|
|
112
|
-
is because Airflow tries to load this file and process it as a Jinja template when
|
|
113
|
-
it ends with ``.sh`` or ``.bash``.
|
|
114
|
-
|
|
115
|
-
If you have Jinja template in your script, do not put any blank space. And add the script's directory
|
|
116
|
-
in the DAG's ``template_searchpath``. If you specify a ``cwd``, Airflow must have write access to
|
|
117
|
-
this directory. The script will be rendered (Jinja template) into a new temporary file in this directory.
|
|
118
|
-
|
|
119
|
-
.. warning::
|
|
120
|
-
|
|
121
|
-
Care should be taken with "user" input or when using Jinja templates in the
|
|
122
|
-
``bash_command``, as this bash operator does not perform any escaping or
|
|
123
|
-
sanitization of the command.
|
|
124
|
-
|
|
125
|
-
This applies mostly to using "dag_run" conf, as that can be submitted via
|
|
126
|
-
users in the Web UI. Most of the default template variables are not at
|
|
127
|
-
risk.
|
|
128
|
-
|
|
129
|
-
For example, do **not** do this:
|
|
130
|
-
|
|
131
|
-
.. code-block:: python
|
|
132
|
-
|
|
133
|
-
bash_task = BashOperator(
|
|
134
|
-
task_id="bash_task",
|
|
135
|
-
bash_command='echo "Here is the message: \'{{ dag_run.conf["message"] if dag_run else "" }}\'"',
|
|
136
|
-
)
|
|
137
|
-
|
|
138
|
-
Instead, you should pass this via the ``env`` kwarg and use double-quotes
|
|
139
|
-
inside the bash_command, as below:
|
|
140
|
-
|
|
141
|
-
.. code-block:: python
|
|
142
|
-
|
|
143
|
-
bash_task = BashOperator(
|
|
144
|
-
task_id="bash_task",
|
|
145
|
-
bash_command="echo \"here is the message: '$message'\"",
|
|
146
|
-
env={"message": '{{ dag_run.conf["message"] if dag_run else "" }}'},
|
|
147
|
-
)
|
|
148
|
-
|
|
149
|
-
.. versionadded:: 2.10.0
|
|
150
|
-
The `output_processor` parameter.
|
|
151
|
-
|
|
152
|
-
"""
|
|
153
|
-
|
|
154
|
-
template_fields: Sequence[str] = ("bash_command", "env", "cwd")
|
|
155
|
-
template_fields_renderers = {"bash_command": "bash", "env": "json"}
|
|
156
|
-
template_ext: Sequence[str] = (".sh", ".bash")
|
|
157
|
-
ui_color = "#f0ede4"
|
|
158
|
-
|
|
159
|
-
def __init__(
|
|
160
|
-
self,
|
|
161
|
-
*,
|
|
162
|
-
bash_command: str | ArgNotSet,
|
|
163
|
-
env: dict[str, str] | None = None,
|
|
164
|
-
append_env: bool = False,
|
|
165
|
-
output_encoding: str = "utf-8",
|
|
166
|
-
skip_on_exit_code: int | Container[int] | None = 99,
|
|
167
|
-
cwd: str | None = None,
|
|
168
|
-
output_processor: Callable[[str], Any] = lambda result: result,
|
|
169
|
-
**kwargs,
|
|
170
|
-
) -> None:
|
|
171
|
-
super().__init__(**kwargs)
|
|
172
|
-
self.bash_command = bash_command
|
|
173
|
-
self.env = env
|
|
174
|
-
self.output_encoding = output_encoding
|
|
175
|
-
self.skip_on_exit_code = (
|
|
176
|
-
skip_on_exit_code
|
|
177
|
-
if isinstance(skip_on_exit_code, Container)
|
|
178
|
-
else [skip_on_exit_code]
|
|
179
|
-
if skip_on_exit_code is not None
|
|
180
|
-
else []
|
|
181
|
-
)
|
|
182
|
-
self.cwd = cwd
|
|
183
|
-
self.append_env = append_env
|
|
184
|
-
self.output_processor = output_processor
|
|
185
|
-
|
|
186
|
-
# When using the @task.bash decorator, the Bash command is not known until the underlying Python
|
|
187
|
-
# callable is executed and therefore set to NOTSET initially. This flag is useful during execution to
|
|
188
|
-
# determine whether the bash_command value needs to re-rendered.
|
|
189
|
-
self._init_bash_command_not_set = isinstance(self.bash_command, ArgNotSet)
|
|
190
|
-
|
|
191
|
-
# Keep a copy of the original bash_command, without the Jinja template rendered.
|
|
192
|
-
# This is later used to determine if the bash_command is a script or an inline string command.
|
|
193
|
-
# We do this later, because the bash_command is not available in __init__ when using @task.bash.
|
|
194
|
-
self._unrendered_bash_command: str | ArgNotSet = bash_command
|
|
195
|
-
|
|
196
|
-
@cached_property
|
|
197
|
-
def subprocess_hook(self):
|
|
198
|
-
"""Returns hook for running the bash command."""
|
|
199
|
-
return SubprocessHook()
|
|
200
|
-
|
|
201
|
-
# TODO: This should be replaced with Task SDK API call
|
|
202
|
-
@staticmethod
|
|
203
|
-
@provide_session
|
|
204
|
-
def refresh_bash_command(ti, session: SASession = NEW_SESSION) -> None:
|
|
205
|
-
"""
|
|
206
|
-
Rewrite the underlying rendered bash_command value for a task instance in the metadatabase.
|
|
207
|
-
|
|
208
|
-
TaskInstance.get_rendered_template_fields() cannot be used because this will retrieve the
|
|
209
|
-
RenderedTaskInstanceFields from the metadatabase which doesn't have the runtime-evaluated bash_command
|
|
210
|
-
value.
|
|
211
|
-
|
|
212
|
-
:meta private:
|
|
213
|
-
"""
|
|
214
|
-
from airflow.models.renderedtifields import RenderedTaskInstanceFields
|
|
215
|
-
|
|
216
|
-
"""Update rendered task instance fields for cases where runtime evaluated, not templated."""
|
|
217
|
-
|
|
218
|
-
rtif = RenderedTaskInstanceFields(ti)
|
|
219
|
-
RenderedTaskInstanceFields.write(rtif, session=session)
|
|
220
|
-
RenderedTaskInstanceFields.delete_old_records(ti.task_id, ti.dag_id, session=session)
|
|
221
|
-
|
|
222
|
-
def get_env(self, context) -> dict:
|
|
223
|
-
"""Build the set of environment variables to be exposed for the bash command."""
|
|
224
|
-
system_env = os.environ.copy()
|
|
225
|
-
env = self.env
|
|
226
|
-
if env is None:
|
|
227
|
-
env = system_env
|
|
228
|
-
else:
|
|
229
|
-
if self.append_env:
|
|
230
|
-
system_env.update(env)
|
|
231
|
-
env = system_env
|
|
232
|
-
|
|
233
|
-
airflow_context_vars = context_to_airflow_vars(context, in_env_var_format=True)
|
|
234
|
-
self.log.debug(
|
|
235
|
-
"Exporting env vars: %s",
|
|
236
|
-
" ".join(f"{k}={v!r}" for k, v in airflow_context_vars.items()),
|
|
237
|
-
)
|
|
238
|
-
env.update(airflow_context_vars)
|
|
239
|
-
return env
|
|
240
|
-
|
|
241
|
-
def execute(self, context: Context):
|
|
242
|
-
bash_path: str = shutil.which("bash") or "bash"
|
|
243
|
-
if self.cwd is not None:
|
|
244
|
-
if not os.path.exists(self.cwd):
|
|
245
|
-
raise AirflowException(f"Can not find the cwd: {self.cwd}")
|
|
246
|
-
if not os.path.isdir(self.cwd):
|
|
247
|
-
raise AirflowException(f"The cwd {self.cwd} must be a directory")
|
|
248
|
-
env = self.get_env(context)
|
|
249
|
-
|
|
250
|
-
# Because the bash_command value is evaluated at runtime using the @task.bash decorator, the
|
|
251
|
-
# RenderedTaskInstanceField data needs to be rewritten and the bash_command value re-rendered -- the
|
|
252
|
-
# latter because the returned command from the decorated callable could contain a Jinja expression.
|
|
253
|
-
# Both will ensure the correct Bash command is executed and that the Rendered Template view in the UI
|
|
254
|
-
# displays the executed command (otherwise it will display as an ArgNotSet type).
|
|
255
|
-
if self._init_bash_command_not_set:
|
|
256
|
-
is_inline_command = self._is_inline_command(bash_command=cast(str, self.bash_command))
|
|
257
|
-
ti = context["ti"]
|
|
258
|
-
self.refresh_bash_command(ti)
|
|
259
|
-
else:
|
|
260
|
-
is_inline_command = self._is_inline_command(bash_command=cast(str, self._unrendered_bash_command))
|
|
261
|
-
|
|
262
|
-
if is_inline_command:
|
|
263
|
-
result = self._run_inline_command(bash_path=bash_path, env=env)
|
|
264
|
-
else:
|
|
265
|
-
result = self._run_rendered_script_file(bash_path=bash_path, env=env)
|
|
266
|
-
|
|
267
|
-
if result.exit_code in self.skip_on_exit_code:
|
|
268
|
-
raise AirflowSkipException(f"Bash command returned exit code {result.exit_code}. Skipping.")
|
|
269
|
-
elif result.exit_code != 0:
|
|
270
|
-
raise AirflowException(
|
|
271
|
-
f"Bash command failed. The command returned a non-zero exit code {result.exit_code}."
|
|
272
|
-
)
|
|
273
|
-
|
|
274
|
-
return self.output_processor(result.output)
|
|
275
|
-
|
|
276
|
-
def _run_inline_command(self, bash_path: str, env: dict) -> SubprocessResult:
|
|
277
|
-
"""Pass the bash command as string directly in the subprocess."""
|
|
278
|
-
return self.subprocess_hook.run_command(
|
|
279
|
-
command=[bash_path, "-c", self.bash_command],
|
|
280
|
-
env=env,
|
|
281
|
-
output_encoding=self.output_encoding,
|
|
282
|
-
cwd=self.cwd,
|
|
283
|
-
)
|
|
284
|
-
|
|
285
|
-
def _run_rendered_script_file(self, bash_path: str, env: dict) -> SubprocessResult:
|
|
286
|
-
"""
|
|
287
|
-
Save the bash command into a file and execute this file.
|
|
288
|
-
|
|
289
|
-
This allows for longer commands, and prevents "Argument list too long error".
|
|
290
|
-
"""
|
|
291
|
-
with working_directory(cwd=self.cwd) as cwd:
|
|
292
|
-
with tempfile.NamedTemporaryFile(mode="w", dir=cwd, suffix=".sh") as file:
|
|
293
|
-
file.write(cast(str, self.bash_command))
|
|
294
|
-
file.flush()
|
|
295
|
-
|
|
296
|
-
bash_script = os.path.basename(file.name)
|
|
297
|
-
return self.subprocess_hook.run_command(
|
|
298
|
-
command=[bash_path, bash_script],
|
|
299
|
-
env=env,
|
|
300
|
-
output_encoding=self.output_encoding,
|
|
301
|
-
cwd=cwd,
|
|
302
|
-
)
|
|
303
|
-
|
|
304
|
-
@classmethod
|
|
305
|
-
def _is_inline_command(cls, bash_command: str) -> bool:
|
|
306
|
-
"""Return True if the bash command is an inline string. False if it's a bash script file."""
|
|
307
|
-
return not bash_command.endswith(tuple(cls.template_ext))
|
|
308
|
-
|
|
309
|
-
def on_kill(self) -> None:
|
|
310
|
-
self.subprocess_hook.send_sigterm()
|
|
@@ -1,39 +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
|
-
from typing import TYPE_CHECKING
|
|
20
|
-
|
|
21
|
-
from airflow.models.baseoperator import BaseOperator
|
|
22
|
-
|
|
23
|
-
if TYPE_CHECKING:
|
|
24
|
-
from airflow.sdk.definitions.context import Context
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
class EmptyOperator(BaseOperator):
|
|
28
|
-
"""
|
|
29
|
-
Operator that does literally nothing.
|
|
30
|
-
|
|
31
|
-
It can be used to group tasks in a DAG.
|
|
32
|
-
The task is evaluated by the scheduler but never processed by the executor.
|
|
33
|
-
"""
|
|
34
|
-
|
|
35
|
-
ui_color = "#e8f7e4"
|
|
36
|
-
inherits_from_empty_operator = True
|
|
37
|
-
|
|
38
|
-
def execute(self, context: Context):
|
|
39
|
-
pass
|