You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by mo...@apache.org on 2023/11/14 14:59:06 UTC
(airflow) 01/01: hooks poc
This is an automated email from the ASF dual-hosted git repository.
mobuchowski pushed a commit to branch hooks-lineage
in repository https://gitbox.apache.org/repos/asf/airflow.git
commit d1aec927d9997585fe4fa2996b2ec98a2ac7c36f
Author: Maciej Obuchowski <ob...@gmail.com>
AuthorDate: Fri Nov 3 16:49:02 2023 +0100
hooks poc
Signed-off-by: Maciej Obuchowski <ob...@gmail.com>
---
airflow/hooks/base.py | 13 +++++
airflow/lineage/hook.py | 60 +++++++++++++++++++++
airflow/operators/python.py | 63 ++++++++++++++++++++++
airflow/providers/amazon/aws/hooks/s3.py | 15 ++++++
airflow/providers/google/cloud/hooks/gcs.py | 11 ++++
.../providers/google/cloud/transfers/s3_to_gcs.py | 16 ++++++
.../providers/openlineage/extractors/manager.py | 8 +++
7 files changed, 186 insertions(+)
diff --git a/airflow/hooks/base.py b/airflow/hooks/base.py
index 0974813c5a..386b2f0b31 100644
--- a/airflow/hooks/base.py
+++ b/airflow/hooks/base.py
@@ -23,6 +23,7 @@ import warnings
from typing import TYPE_CHECKING, Any
from airflow.exceptions import RemovedInAirflow3Warning
+from airflow.lineage.hook import get_hook_lineage_collector
from airflow.typing_compat import Protocol
from airflow.utils.log.logging_mixin import LoggingMixin
@@ -96,6 +97,18 @@ class BaseHook(LoggingMixin):
def get_ui_field_behaviour(cls) -> dict[str, Any]:
return {}
+ @classmethod
+ def add_input_dataset(cls, name: str, namespace: str):
+ from openlineage.client.run import Dataset as OpenLineageDataset
+
+ get_hook_lineage_collector().add_input(OpenLineageDataset(namespace=namespace, name=name))
+
+ @classmethod
+ def add_output_dataset(cls, name: str, namespace: str):
+ from openlineage.client.run import Dataset as OpenLineageDataset
+
+ get_hook_lineage_collector().add_output(OpenLineageDataset(namespace=namespace, name=name))
+
class DiscoverableHook(Protocol):
"""
diff --git a/airflow/lineage/hook.py b/airflow/lineage/hook.py
new file mode 100644
index 0000000000..6dee97f030
--- /dev/null
+++ b/airflow/lineage/hook.py
@@ -0,0 +1,60 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+from __future__ import annotations
+
+import typing
+
+from airflow.compat.functools import cache
+from airflow.utils.module_loading import import_string
+
+if typing.TYPE_CHECKING:
+ from openlineage.client.run import Dataset as OpenLineageDataset
+
+
+class LineageCollector:
+ """Info."""
+
+ def __init__(self):
+ self.inputs: list[OpenLineageDataset] = []
+ self.outputs: list[OpenLineageDataset] = []
+
+ def add_input(self, input: OpenLineageDataset):
+ self.inputs.append(input)
+
+ def add_output(self, output: OpenLineageDataset):
+ self.outputs.append(output)
+
+ @property
+ def collected(self) -> tuple[list[OpenLineageDataset], list[OpenLineageDataset]]:
+ return self.inputs, self.outputs
+
+ def has_collected(self) -> bool:
+ return len(self.inputs) != 0 and len(self.outputs) != 0
+
+
+_collector = LineageCollector()
+
+
+@cache
+def does_openlineage_exist() -> bool:
+ is_disabled = import_string("apache.airflow.providers.openlineage.plugin._is_disabled")
+ return is_disabled and is_disabled()
+
+
+def get_hook_lineage_collector() -> LineageCollector:
+ return _collector
diff --git a/airflow/operators/python.py b/airflow/operators/python.py
index 5a4cf9c2a2..17a1d8233d 100644
--- a/airflow/operators/python.py
+++ b/airflow/operators/python.py
@@ -45,6 +45,7 @@ from airflow.exceptions import (
DeserializingResultError,
RemovedInAirflow3Warning,
)
+from airflow.lineage.hook import get_hook_lineage_collector
from airflow.models.baseoperator import BaseOperator
from airflow.models.skipmixin import SkipMixin
from airflow.models.taskinstance import _CURRENT_CONTEXT
@@ -304,6 +305,68 @@ class ShortCircuitOperator(PythonOperator, SkipMixin):
# returns the result of the super execute method as it is instead of returning None
return condition
+ def get_openlineage_facets_on_complete(self):
+ from airflow.providers.openlineage.extractors import OperatorLineage
+
+ inputs, outputs = get_hook_lineage_collector().collected
+ if inputs or outputs:
+ return OperatorLineage(inputs=inputs, outputs=outputs)
+ else:
+ return self._execute_extraction()
+
+ def _execute_extraction(self):
+ from openlineage.client.facet import SourceCodeJobFacet
+
+ from airflow.providers.openlineage.extractors.base import OperatorLineage
+ from airflow.providers.openlineage.plugins.facets import (
+ UnknownOperatorAttributeRunFacet,
+ UnknownOperatorInstance,
+ )
+ from airflow.providers.openlineage.utils.utils import (
+ get_filtered_unknown_operator_keys,
+ is_source_enabled,
+ )
+
+ source_code = self.get_source_code(self.python_callable)
+ job_facet: dict = {}
+ if is_source_enabled() and source_code:
+ job_facet = {
+ "sourceCode": SourceCodeJobFacet(
+ language="python",
+ # We're on worker and should have access to DAG files
+ source=source_code,
+ )
+ }
+ return OperatorLineage(
+ job_facets=job_facet,
+ run_facets={
+ # The PythonOperator is recorded as an "unknownSource" even though we have an
+ # extractor, as the data lineage cannot be determined from the operator
+ # directly.
+ "unknownSourceAttribute": UnknownOperatorAttributeRunFacet(
+ unknownItems=[
+ UnknownOperatorInstance(
+ name="PythonOperator",
+ properties=get_filtered_unknown_operator_keys(self),
+ )
+ ]
+ )
+ },
+ )
+
+ def get_source_code(self, callable: Callable) -> str | None:
+ try:
+ return inspect.getsource(callable)
+ except TypeError:
+ # Trying to extract source code of builtin_function_or_method
+ return str(callable)
+ except OSError:
+ self.log.warning(
+ "Can't get source code facet of PythonOperator %s",
+ self.task_id,
+ )
+ return None
+
class _BasePythonVirtualenvOperator(PythonOperator, metaclass=ABCMeta):
BASE_SERIALIZABLE_CONTEXT_KEYS = {
diff --git a/airflow/providers/amazon/aws/hooks/s3.py b/airflow/providers/amazon/aws/hooks/s3.py
index ef54dc0099..b3a32ff01b 100644
--- a/airflow/providers/amazon/aws/hooks/s3.py
+++ b/airflow/providers/amazon/aws/hooks/s3.py
@@ -1394,8 +1394,18 @@ class S3Hook(AwsBaseHook):
file_path.parent.mkdir(exist_ok=True, parents=True)
file = open(file_path, "wb")
+
+ self.add_output_dataset(
+ namespace="file://", # type: ignore[union-attr]
+ name=str(file_path), # type: ignore[union-attr]
+ )
+
else:
file = NamedTemporaryFile(dir=local_path, prefix="airflow_tmp_", delete=False) # type: ignore
+ self.add_output_dataset(
+ namespace="file://", # type: ignore[union-attr]
+ name=str(local_path or gettempdir()), # type: ignore[union-attr]
+ )
with file:
s3_obj.download_fileobj(
@@ -1404,6 +1414,11 @@ class S3Hook(AwsBaseHook):
Config=self.transfer_config,
)
+ self.add_input_dataset(
+ namespace="s3://" + bucket_name, # type: ignore[attr-defined,operator]
+ name=key, # type: ignore[attr-defined]
+ )
+
return file.name
def generate_presigned_url(
diff --git a/airflow/providers/google/cloud/hooks/gcs.py b/airflow/providers/google/cloud/hooks/gcs.py
index d8bb36037f..6f40204eb2 100644
--- a/airflow/providers/google/cloud/hooks/gcs.py
+++ b/airflow/providers/google/cloud/hooks/gcs.py
@@ -222,6 +222,15 @@ class GCSHook(GoogleBaseHook):
destination_bucket.name, # type: ignore[union-attr]
)
+ self.add_input_dataset(
+ namespace="gs://" + source_bucket.name, # type: ignore[attr-defined]
+ name=source_object.name, # type: ignore[attr-defined]
+ )
+ self.add_output_dataset(
+ namespace="gs://" + destination_bucket.name, # type: ignore[union-attr]
+ name=destination_object.name, # type: ignore[union-attr]
+ )
+
def rewrite(
self,
source_bucket: str,
@@ -531,6 +540,8 @@ class GCSHook(GoogleBaseHook):
bucket = client.bucket(bucket_name, user_project=user_project)
blob = bucket.blob(blob_name=object_name, chunk_size=chunk_size)
+ self.add_output_dataset(namespace="gs://" + bucket_name, name=object_name)
+
if metadata:
blob.metadata = metadata
diff --git a/airflow/providers/google/cloud/transfers/s3_to_gcs.py b/airflow/providers/google/cloud/transfers/s3_to_gcs.py
index 37d438f3de..b9eeb675bb 100644
--- a/airflow/providers/google/cloud/transfers/s3_to_gcs.py
+++ b/airflow/providers/google/cloud/transfers/s3_to_gcs.py
@@ -168,6 +168,7 @@ class S3ToGCSOperator(S3ListOperator):
if poll_interval <= 0:
raise ValueError("Invalid value for poll_interval. Expected value greater than 0")
self.poll_interval = poll_interval
+ self.transferred_s3_objects: Sequence[str] = []
def _check_inputs(self) -> None:
if self.dest_gcs and not gcs_object_is_directory(self.dest_gcs):
@@ -192,6 +193,8 @@ class S3ToGCSOperator(S3ListOperator):
if not self.replace:
s3_objects = self.exclude_existing_objects(s3_objects=s3_objects, gcs_hook=gcs_hook)
+ self.transferred_s3_objects = s3_objects
+
s3_hook = S3Hook(aws_conn_id=self.aws_conn_id, verify=self.verify)
if not s3_objects:
self.log.info("In sync, no files needed to be uploaded to Google Cloud Storage")
@@ -246,6 +249,7 @@ class S3ToGCSOperator(S3ListOperator):
return s3_object
def transfer_files(self, s3_objects: list[str], gcs_hook: GCSHook, s3_hook: S3Hook) -> None:
+ self.log.info("TRANSFERRING")
if s3_objects:
dest_gcs_bucket, dest_gcs_object_prefix = _parse_gcs_url(self.dest_gcs)
for obj in s3_objects:
@@ -346,3 +350,15 @@ class S3ToGCSOperator(S3ListOperator):
gcp_conn_id=self.gcp_conn_id,
impersonation_chain=self.google_impersonation_chain,
)
+
+ def get_openlineage_facets_on_start(self):
+ from openlineage.client.run import Dataset
+
+ from airflow.lineage.hook import get_hook_lineage_collector
+ from airflow.providers.openlineage.extractors import OperatorLineage
+
+ _, outputs = get_hook_lineage_collector().collected
+ return OperatorLineage(
+ inputs=[Dataset(namespace="s3://" + self.bucket, name=x) for x in self.transferred_s3_objects],
+ outputs=outputs,
+ )
diff --git a/airflow/providers/openlineage/extractors/manager.py b/airflow/providers/openlineage/extractors/manager.py
index 480ffc9f39..5c54515429 100644
--- a/airflow/providers/openlineage/extractors/manager.py
+++ b/airflow/providers/openlineage/extractors/manager.py
@@ -82,6 +82,10 @@ class ExtractorManager(LoggingMixin):
f"airflow_run_id={dagrun.run_id} "
)
+ from airflow.lineage.hook import get_hook_lineage_collector
+
+ self.log.debug(f"Collected lineage from hooks: {get_hook_lineage_collector().has_collected()}")
+
if extractor:
# Extracting advanced metadata is only possible when extractor for particular operator
# is defined. Without it, we can't extract any input or output data.
@@ -104,6 +108,10 @@ class ExtractorManager(LoggingMixin):
self.log.warning(
"Failed to extract metadata using found extractor %s - %s %s", extractor, e, task_info
)
+ elif get_hook_lineage_collector().has_collected():
+ self.log.debug("Found lineage collected from hooks")
+ inputs, outputs = get_hook_lineage_collector().collected
+ return OperatorLineage(inputs=inputs, outputs=outputs)
else:
self.log.debug("Unable to find an extractor %s", task_info)