mobuchowski commented on code in PR #29940:
URL: https://github.com/apache/airflow/pull/29940#discussion_r1135361660


##########
airflow/providers/openlineage/plugins/adapter.py:
##########
@@ -0,0 +1,302 @@
+# 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 os
+import uuid
+from typing import TYPE_CHECKING
+
+import requests.exceptions
+
+from airflow.providers.openlineage import version as 
OPENLINEAGE_PROVIDER_VERSION
+from airflow.providers.openlineage.extractors import OperatorLineage
+from airflow.providers.openlineage.utils import redact_with_exclusions
+from airflow.utils.log.logging_mixin import LoggingMixin
+from openlineage.client import OpenLineageClient, set_producer
+from openlineage.client.facet import (
+    BaseFacet,
+    DocumentationJobFacet,
+    ErrorMessageRunFacet,
+    NominalTimeRunFacet,
+    OwnershipJobFacet,
+    OwnershipJobFacetOwners,
+    ParentRunFacet,
+    ProcessingEngineRunFacet,
+    SourceCodeLocationJobFacet,
+)
+from openlineage.client.run import Job, Run, RunEvent, RunState
+
+if TYPE_CHECKING:
+    from airflow.models.dagrun import DagRun
+
+
+_DAG_DEFAULT_NAMESPACE = "default"
+
+_DAG_NAMESPACE = os.getenv("OPENLINEAGE_NAMESPACE", _DAG_DEFAULT_NAMESPACE)
+
+_PRODUCER = f"https://github.com/apache/airflow/tree/providers-openlineage/"; 
f"{OPENLINEAGE_PROVIDER_VERSION}"
+
+set_producer(_PRODUCER)
+
+
+class OpenLineageAdapter(LoggingMixin):
+    """
+    Adapter for translating Airflow metadata to OpenLineage events,
+    instead of directly creating them from Airflow code.
+    """
+
+    def __init__(self, client=None):
+        super().__init__()
+        self._client = client
+
+    def get_or_create_openlineage_client(self) -> OpenLineageClient:
+        if not self._client:
+            self._client = OpenLineageClient.from_environment()
+        return self._client
+
+    def build_dag_run_id(self, dag_id, dag_run_id):
+        return str(uuid.uuid3(uuid.NAMESPACE_URL, 
f"{_DAG_NAMESPACE}.{dag_id}.{dag_run_id}"))
+
+    @staticmethod
+    def build_task_instance_run_id(task_id, execution_date, try_number):
+        return str(
+            uuid.uuid3(
+                uuid.NAMESPACE_URL,
+                f"{_DAG_NAMESPACE}.{task_id}.{execution_date}.{try_number}",
+            )
+        )
+
+    def emit(self, event: RunEvent):
+        event = redact_with_exclusions(event)
+        try:
+            return self.get_or_create_openlineage_client().emit(event)
+        except requests.exceptions.RequestException:
+            self.log.exception(f"Failed to emit OpenLineage event of id 
{event.run.runId}")
+
+    def start_task(
+        self,
+        run_id: str,
+        job_name: str,
+        job_description: str,
+        event_time: str,
+        parent_job_name: str | None,
+        parent_run_id: str | None,
+        code_location: str | None,
+        nominal_start_time: str,
+        nominal_end_time: str,
+        owners: list[str],
+        task: OperatorLineage | None,
+        run_facets: dict[str, type[BaseFacet]] | None = None,  # Custom run 
facets
+    ) -> str:
+        """
+        Emits openlineage event of type START
+        :param run_id: globally unique identifier of task in dag run
+        :param job_name: globally unique identifier of task in dag
+        :param job_description: user provided description of job
+        :param event_time:
+        :param parent_job_name: the name of the parent job (typically the DAG,
+                but possibly a task group)
+        :param parent_run_id: identifier of job spawning this task
+        :param code_location: file path or URL of DAG file
+        :param nominal_start_time: scheduled time of dag run
+        :param nominal_end_time: following schedule of dag run
+        :param owners: list of owners of DAG
+        :param task: metadata container with information extracted from 
operator
+        :param run_facets: custom run facets
+        :return:

Review Comment:
   Actually, removed return value - we don't need this now.



##########
airflow/providers/openlineage/plugins/facets.py:
##########
@@ -0,0 +1,116 @@
+# 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
+
+from attrs import define, field
+
+from airflow.providers.openlineage import version as 
OPENLINEAGE_AIRFLOW_VERSION
+from airflow.version import version as AIRFLOW_VERSION
+from openlineage.client.facet import BaseFacet
+from openlineage.client.utils import RedactMixin
+
+
+@define(slots=False)
+class AirflowVersionRunFacet(BaseFacet):
+    """Run facet containing task and DAG info"""
+
+    operator: str = field()
+    taskInfo: dict[str, object] = field()
+    airflowVersion: str = field()
+    openlineageAirflowVersion: str = field()
+
+    _additional_skip_redact: list[str] = [
+        "operator",
+        "airflowVersion",
+        "openlineageAirflowVersion",
+    ]
+
+    @classmethod
+    def from_dagrun_and_task(cls, dagrun, task):
+        # task.__dict__ may contain values uncastable to str
+        from airflow.providers.openlineage.utils import get_operator_class, 
to_json_encodable
+
+        task_info = to_json_encodable(task)
+        task_info["dag_run"] = to_json_encodable(dagrun)
+
+        return cls(
+            
operator=f"{get_operator_class(task).__module__}.{get_operator_class(task).__name__}",
+            taskInfo=task_info,
+            airflowVersion=AIRFLOW_VERSION,
+            openlineageAirflowVersion=OPENLINEAGE_AIRFLOW_VERSION,
+        )
+
+
+@define(slots=False)
+class AirflowRunArgsRunFacet(BaseFacet):
+    """Run facet pointing if DAG was triggered manually"""
+
+    externalTrigger: bool = field(default=False)
+
+    _additional_skip_redact: list[str] = ["externalTrigger"]
+
+
+@define(slots=False)
+class AirflowMappedTaskRunFacet(BaseFacet):
+    """Run facet containing information about mapped tasks"""
+
+    mapIndex: int = field()
+    operatorClass: str = field()
+
+    _additional_skip_redact: list[str] = ["operatorClass"]
+
+    @classmethod
+    def from_task_instance(cls, task_instance):
+        task = task_instance.task
+        from airflow.providers.openlineage.utils import get_operator_class
+
+        return cls(
+            mapIndex=task_instance.map_index,
+            
operatorClass=f"{get_operator_class(task).__module__}.{get_operator_class(task).__name__}",
+        )
+
+
+@define(slots=False)
+class AirflowRunFacet(BaseFacet):
+    """Composite Airflow run facet."""
+
+    dag: dict = field()
+    dagRun: dict = field()
+    task: dict = field()
+    taskInstance: dict = field()
+    taskUuid: str = field()

Review Comment:
   Removed. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscr...@airflow.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to