|
| 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 typing import TYPE_CHECKING, Sequence |
| 21 | + |
| 22 | +from google.api_core.operation import Operation |
| 23 | + |
| 24 | +from airflow import AirflowException |
| 25 | +from airflow.providers.google.cloud.hooks.dataproc_metastore import DataprocMetastoreHook |
| 26 | +from airflow.providers.google.cloud.hooks.gcs import parse_json_from_gcs |
| 27 | +from airflow.sensors.base import BaseSensorOperator |
| 28 | + |
| 29 | +if TYPE_CHECKING: |
| 30 | + from airflow.utils.context import Context |
| 31 | + |
| 32 | + |
| 33 | +class MetastoreHivePartitionSensor(BaseSensorOperator): |
| 34 | + """ |
| 35 | + Waits for partitions to show up in Hive. |
| 36 | + This sensor uses Google Cloud SDK and passes requests via gRPC. |
| 37 | +
|
| 38 | + :param service_id: Required. Dataproc Metastore service id. |
| 39 | + :param region: Required. The ID of the Google Cloud region that the service belongs to. |
| 40 | + :param table: Required. Name of the partitioned table |
| 41 | + :param partitions: List of table partitions to wait for. |
| 42 | + A name of a partition should look like "ds=1", or "a=1/b=2" in case of nested partitions. |
| 43 | + Note that you cannot use logical or comparison operators as in HivePartitionSensor. |
| 44 | + If not specified then the sensor will wait for at least one partition regardless its name. |
| 45 | + :param gcp_conn_id: Airflow Google Cloud connection ID. |
| 46 | + :param impersonation_chain: Optional service account to impersonate using short-term |
| 47 | + credentials, or chained list of accounts required to get the access_token |
| 48 | + of the last account in the list, which will be impersonated in the request. |
| 49 | + If set as a string, the account must grant the originating account |
| 50 | + the Service Account Token Creator IAM role. |
| 51 | + If set as a sequence, the identities from the list must grant |
| 52 | + Service Account Token Creator IAM role to the directly preceding identity, with first |
| 53 | + account from the list granting this role to the originating account. |
| 54 | + """ |
| 55 | + |
| 56 | + template_fields: Sequence[str] = ( |
| 57 | + "service_id", |
| 58 | + "region", |
| 59 | + "table", |
| 60 | + "partitions", |
| 61 | + "impersonation_chain", |
| 62 | + ) |
| 63 | + |
| 64 | + def __init__( |
| 65 | + self, |
| 66 | + service_id: str, |
| 67 | + region: str, |
| 68 | + table: str, |
| 69 | + partitions: list[str] | None, |
| 70 | + gcp_conn_id: str = "google_cloud_default", |
| 71 | + impersonation_chain: str | Sequence[str] | None = None, |
| 72 | + *args, |
| 73 | + **kwargs, |
| 74 | + ): |
| 75 | + super().__init__(*args, **kwargs) |
| 76 | + self.service_id = service_id |
| 77 | + self.region = region |
| 78 | + self.table = table |
| 79 | + self.partitions = partitions or [] |
| 80 | + self.gcp_conn_id = gcp_conn_id |
| 81 | + self.impersonation_chain = impersonation_chain |
| 82 | + |
| 83 | + def poke(self, context: Context) -> bool: |
| 84 | + hook = DataprocMetastoreHook( |
| 85 | + gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain |
| 86 | + ) |
| 87 | + operation: Operation = hook.list_hive_partitions( |
| 88 | + region=self.region, service_id=self.service_id, table=self.table, partition_names=self.partitions |
| 89 | + ) |
| 90 | + metadata = hook.wait_for_operation(timeout=self.timeout, operation=operation) |
| 91 | + result_manifest_uri: str = metadata.result_manifest_uri |
| 92 | + self.log.info("Received result manifest URI: %s", result_manifest_uri) |
| 93 | + |
| 94 | + self.log.info("Extracting result manifest") |
| 95 | + manifest: dict = parse_json_from_gcs(gcp_conn_id=self.gcp_conn_id, file_uri=result_manifest_uri) |
| 96 | + if not (manifest and isinstance(manifest, dict)): |
| 97 | + raise AirflowException( |
| 98 | + f"Failed to extract result manifest. " |
| 99 | + f"Expected not empty dict, but this was received: {manifest}" |
| 100 | + ) |
| 101 | + |
| 102 | + if manifest.get("status", {}).get("code") != 0: |
| 103 | + raise AirflowException(f"Request failed: {manifest.get('message')}") |
| 104 | + |
| 105 | + # Extract actual query results |
| 106 | + result_base_uri = result_manifest_uri.rsplit("/", 1)[0] |
| 107 | + results = (f"{result_base_uri}//{filename}" for filename in manifest.get("filenames", [])) |
| 108 | + found_partitions = sum( |
| 109 | + len(parse_json_from_gcs(gcp_conn_id=self.gcp_conn_id, file_uri=uri).get("rows", [])) |
| 110 | + for uri in results |
| 111 | + ) |
| 112 | + |
| 113 | + # Return True if we got all requested partitions. |
| 114 | + # If no partitions were given in the request, then we expect to find at least one. |
| 115 | + return found_partitions > 0 and found_partitions >= len(set(self.partitions)) |
0 commit comments