Yanislava commented on code in PR #77242: URL: https://github.com/apache/airflow/pull/77242#discussion_r4666721418
########## providers/http/src/airflow/providers/http/sensors/remote_external_task.py: ########## @@ -0,0 +1,353 @@ +# +# 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. +"""Sensor that waits for a DAG or tasks in another Airflow instance through its REST API.""" + +from __future__ import annotations + +import datetime +import warnings +from collections.abc import Sequence +from typing import TYPE_CHECKING, Any + +from requests.auth import AuthBase + +from airflow.providers.common.compat.sdk import ( + AirflowFailException, + AirflowOptionalProviderFeatureException, + BaseSensorOperator, +) +from airflow.providers.http.exceptions import RemoteAirflowApiUnavailableException +from airflow.providers.http.hooks.http import HttpHook + +try: + from airflow.providers.standard.sensors.external_task import ExternalTaskSensor +except ImportError as e: + raise AirflowOptionalProviderFeatureException(e) + +if TYPE_CHECKING: + from requests import PreparedRequest, Response + + from airflow.sdk import Context + +SUPPORTED_API_VERSIONS = ("v1", "v2") +# 429 Too Many Requests and 5xx can be temporary problems of the remote Airflow: let retries handle them. +RETRYABLE_STATUS_CODES = frozenset({429}) +TASK_INSTANCES_PAGE_LIMIT = 100 + + +class _BearerTokenAuth(AuthBase): + """Send an Airflow 3 API access token in the ``Authorization`` header.""" + + def __init__(self, token: str) -> None: + self.token = token + + def __call__(self, request: PreparedRequest) -> PreparedRequest: + request.headers["Authorization"] = f"Bearer {self.token}" + return request + + +class RemoteExternalTaskSensor(ExternalTaskSensor): + """ + Wait for a DAG, or tasks of a DAG, in another Airflow instance to reach a state. + + Works like :class:`~airflow.providers.standard.sensors.external_task.ExternalTaskSensor` and takes + the same arguments, but reads the states from the REST API of a remote Airflow instead of the + metadata database of the Airflow the sensor runs in. + + The remote Airflow is reached through an HTTP connection: host (and port) of its API server or + webserver, and optionally a login and password. + + * ``api_version="v1"`` for a remote Airflow 2: the stable REST API ``/api/v1``. The login and + password, if set, are sent with basic authentication. + * ``api_version="v2"`` for a remote Airflow 3: the public REST API ``/api/v2``. The login and + password, if set, are exchanged for an access token at ``/auth/token`` on every poke. + + The external DAG run is matched by its logical date (``execution_date`` in Airflow 2), computed + from the logical date of the sensor's own run with ``execution_delta`` or ``execution_date_fn`` + exactly as in ``ExternalTaskSensor``. + + .. seealso:: + For more information on how to use this sensor, take a look at the guide: + :ref:`howto/operator:RemoteExternalTaskSensor` + + :param http_conn_id: The :ref:`HTTP connection <howto/connection:http>` to the remote Airflow. + :param api_version: ``"v1"`` for a remote Airflow 2, ``"v2"`` for a remote Airflow 3. + + Task groups (``external_task_group_id``) are not supported yet. Deferrable mode is not supported + yet either: with ``deferrable=True`` the sensor warns and runs as a regular sensor. + ``check_existence=True`` checks the DAG and tasks in the remote Airflow before the first poke. + """ + + template_fields = [*ExternalTaskSensor.template_fields, "http_conn_id"] + # ExternalDagLink of the parent points to the UI of the Airflow the sensor runs in. + operator_extra_links: list = [] + + def __init__( + self, + *, + http_conn_id: str, + api_version: str = "v2", + **kwargs: Any, + ) -> None: + if api_version not in SUPPORTED_API_VERSIONS: + raise ValueError( + f"api_version must be one of {SUPPORTED_API_VERSIONS}: " + "'v1' for a remote Airflow 2, 'v2' for a remote Airflow 3." + ) + super().__init__(**kwargs) + if self.deferrable: + # deferrable defaults to [operators] default_deferrable, so raising would break every + # instance of this sensor where that option is on. + warnings.warn( + "RemoteExternalTaskSensor does not support deferrable mode yet; it runs as a regular " + "sensor (poke or reschedule mode).", + UserWarning, + stacklevel=2, + ) + self.deferrable = False + if self.external_task_group_id: + raise ValueError("RemoteExternalTaskSensor does not support external_task_group_id yet.") + self.http_conn_id = http_conn_id + self.api_version = api_version + self._access_token: str | None = None + + # --- connecting to the remote Airflow ------------------------------------------------------------ + + def _get_remote_api_hook(self, method: str) -> HttpHook: + """HttpHook for the remote Airflow API, authenticated for the configured API version.""" + if self.api_version == "v2" and self._access_token: + token = self._access_token + return HttpHook( + method=method, + http_conn_id=self.http_conn_id, + auth_type=lambda *_: _BearerTokenAuth(token), + ) + # v1 with a login: HttpHook uses basic authentication. No login: no authentication. + return HttpHook(method=method, http_conn_id=self.http_conn_id) + + def _fetch_access_token(self) -> str | None: + """Exchange the connection login and password for an Airflow 3 API access token.""" + conn = HttpHook.get_connection(self.http_conn_id) + if not conn.login: + return None + response = HttpHook(method="POST", http_conn_id=self.http_conn_id).run( + "auth/token", + json={"username": conn.login, "password": conn.password or ""}, + extra_options={"check_response": False}, + ) + self._raise_for_remote_error(response) + return response.json()["access_token"] + + def _build_remote_api_endpoint(self, path: str) -> str: + return f"api/{self.api_version}/{path.lstrip('/')}" + + @staticmethod + def _raise_for_remote_error(response: Response) -> None: + if response.status_code < 400: + return + message = ( + f"{response.request.method} {response.url} returned {response.status_code}: {response.text[:500]}" + ) + if response.status_code >= 500 or response.status_code in RETRYABLE_STATUS_CODES: + # The remote Airflow may be restarting or overloaded: fail this try, keep the task retries. + raise RemoteAirflowApiUnavailableException(message) + # A wrong URL, filter or credentials give the same error on the next try: fail without retries. + raise AirflowFailException(message) + + # --- asking the remote Airflow ------------------------------------------------------------------- + + def _count_remote_records(self, path: str, filters: dict[str, Any]) -> int: + """Return how many records the remote list endpoint finds for the filters.""" + # Only the total is needed: one record is enough, total_entries is still the full count. + response = self._get_remote_api_hook("POST").run( + self._build_remote_api_endpoint(path), + json={**filters, "page_limit": 1}, + extra_options={"check_response": False}, + ) + self._raise_for_remote_error(response) + return int(response.json()["total_entries"]) + + def _build_exact_date_filter(self, date: datetime.datetime) -> dict[str, str]: + """Filter that matches exactly this date: the list endpoints only have from/to date filters.""" + date_field = "execution_date" if self.api_version == "v1" else "logical_date" + date_in_utc = date.astimezone(datetime.UTC).isoformat() Review Comment: Thanks for the review! Good catch, fixed in 45bb3f8043: naive dates are now made aware with timezone.coerce_datetime, so they are read in Airflow's default time zone (UTC unless configured otherwise) rather than the worker host's local time, and there is a test with the host in a UTC+7 zone. CI is green https://github.com/Yanislava/airflow/actions/runs/45179142137 -- 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: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
