# 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 asyncio
from collections.abc import AsyncIterator
from functools import cached_property
from typing import TYPE_CHECKING, Any
from botocore.exceptions import ClientError
if TYPE_CHECKING:
from airflow.providers.amazon.aws.hooks.base_aws import AwsGenericHook
from airflow.providers.amazon.aws.hooks.glue import (
GlueDataQualityHook,
GlueJobHook,
format_glue_logs,
get_glue_log_group_names,
)
from airflow.providers.amazon.aws.hooks.glue_catalog import GlueCatalogHook
from airflow.providers.amazon.aws.hooks.logs import AwsLogsHook
from airflow.providers.amazon.aws.triggers.base import AwsBaseWaiterTrigger
from airflow.triggers.base import BaseTrigger, TriggerEvent
[docs]
class GlueJobCompleteTrigger(AwsBaseWaiterTrigger):
"""
Watches for a glue job, triggers when it finishes.
:param job_name: glue job name
:param run_id: the ID of the specific run to watch for that job
:param verbose: whether to print the job's logs in airflow logs or not
:param waiter_delay: The amount of time in seconds to wait between attempts. (default: 60)
:param waiter_max_attempts: The maximum number of attempts to be made. (default: 75)
:param aws_conn_id: The Airflow connection used for AWS credentials
:param region_name: Optional aws region name (example: us-east-1). Uses region from connection
if not specified.
:param verify: Whether or not to verify SSL certificates.
:param botocore_config: Configuration dictionary (key-values) for botocore client.
"""
def __init__(
self,
job_name: str,
run_id: str,
verbose: bool = False,
waiter_delay: int = 60,
waiter_max_attempts: int = 75,
aws_conn_id: str | None = "aws_default",
region_name: str | None = None,
verify: bool | str | None = None,
botocore_config: dict | None = None,
):
super().__init__(
serialized_fields={"job_name": job_name, "run_id": run_id, "verbose": verbose},
waiter_name="job_complete",
waiter_args={"JobName": job_name, "RunId": run_id},
failure_message="AWS Glue job failed.",
status_message="Status of AWS Glue job is",
status_queries=["JobRun.JobRunState", "JobRun.ErrorMessage"],
return_key="run_id",
return_value=run_id,
waiter_delay=waiter_delay,
waiter_max_attempts=waiter_max_attempts,
aws_conn_id=aws_conn_id,
region_name=region_name,
verify=verify,
botocore_config=botocore_config,
)
[docs]
self.job_name = job_name
[docs]
def hook(self) -> AwsGenericHook:
return GlueJobHook(
aws_conn_id=self.aws_conn_id,
region_name=self.region_name,
verify=self.verify,
config=self.botocore_config,
)
[docs]
async def run(self) -> AsyncIterator[TriggerEvent]:
if not self.verbose:
async for event in super().run():
yield event
return
hook = self.hook()
async with (
await hook.get_async_conn() as glue_client,
await AwsLogsHook(
aws_conn_id=self.aws_conn_id, region_name=self.region_name
).get_async_conn() as logs_client,
):
# Get log group names from job run metadata
job_run_resp = await glue_client.get_job_run(JobName=self.job_name, RunId=self.run_id)
log_group_output, log_group_error = get_glue_log_group_names(job_run_resp["JobRun"])
output_token: str | None = None
error_token: str | None = None
for _attempt in range(self.attempts):
# Fetch current job state
resp = await glue_client.get_job_run(JobName=self.job_name, RunId=self.run_id)
job_run_state = resp["JobRun"]["JobRunState"]
# Fetch and print logs from both output and error streams
try:
output_token = await self._forward_logs(
logs_client, log_group_output, self.run_id, output_token
)
error_token = await self._forward_logs(
logs_client, log_group_error, self.run_id, error_token
)
except ClientError as e:
self.log.error(
"Failed to fetch logs for Glue Job %s Run %s: %s",
self.job_name,
self.run_id,
e,
)
yield TriggerEvent(
{
"status": "error",
"message": f"Failed to fetch logs for Glue Job {self.job_name} Run {self.run_id}: {e}",
self.return_key: self.return_value,
}
)
return
if job_run_state in ("FAILED", "TIMEOUT"):
yield TriggerEvent(
{
"status": "error",
"message": f"Glue Job {self.job_name} Run {self.run_id}"
f" exited with state: {job_run_state}",
self.return_key: self.return_value,
}
)
return
if job_run_state in ("SUCCEEDED", "STOPPED"):
self.log.info(
"Exiting Job %s Run %s State: %s",
self.job_name,
self.run_id,
job_run_state,
)
yield TriggerEvent({"status": "success", self.return_key: self.return_value})
return
self.log.info(
"Polling for AWS Glue Job %s current run state: %s",
self.job_name,
job_run_state,
)
await asyncio.sleep(self.waiter_delay)
yield TriggerEvent(
{
"status": "error",
"message": f"Glue Job {self.job_name} Run {self.run_id}"
f" waiter exceeded max attempts ({self.attempts})",
self.return_key: self.return_value,
}
)
async def _forward_logs(
self,
logs_client: Any,
log_group: str,
log_stream: str,
next_token: str | None,
) -> str | None:
# Matches the format used by the synchronous GlueJobHook.print_job_logs.
fetched_logs: list[str] = []
while True:
token_arg: dict[str, str] = {"nextToken": next_token} if next_token else {}
try:
response = await logs_client.get_log_events(
logGroupName=log_group,
logStreamName=log_stream,
startFromHead=True,
**token_arg,
)
except ClientError as e:
if e.response["Error"]["Code"] == "ResourceNotFoundException":
region = logs_client.meta.region_name
self.log.warning(
"No new Glue driver logs so far.\n"
"If this persists, check the CloudWatch dashboard at: %r.",
f"https://{region}.console.aws.amazon.com/cloudwatch/home",
)
return None
raise
events = response["events"]
fetched_logs.extend(event["message"] for event in events)
if not events or next_token == response["nextForwardToken"]:
break
next_token = response["nextForwardToken"]
self.log.info(format_glue_logs(fetched_logs, log_group))
return response.get("nextForwardToken")
[docs]
class GlueCatalogPartitionTrigger(BaseTrigger):
"""
Asynchronously waits for a partition to show up in AWS Glue Catalog.
:param database_name: The name of the catalog database where the partitions reside.
:param table_name: The name of the table to wait for, supports the dot
notation (my_database.my_table)
:param expression: The partition clause to wait for. This is passed as
is to the AWS Glue Catalog API's get_partitions function,
and supports SQL like notation as in ``ds='2015-01-01'
AND type='value'`` and comparison operators as in ``"ds>=2015-01-01"``.
See https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-catalog-partitions.html
#aws-glue-api-catalog-partitions-GetPartitions
:param aws_conn_id: ID of the Airflow connection where
credentials and extra configuration are stored
:param region_name: Optional aws region name (example: us-east-1). Uses region from connection
if not specified.
:param waiter_delay: Number of seconds to wait between two checks. Default is 60 seconds.
"""
def __init__(
self,
database_name: str,
table_name: str,
expression: str = "",
waiter_delay: int = 60,
aws_conn_id: str | None = "aws_default",
region_name: str | None = None,
verify: bool | str | None = None,
botocore_config: dict | None = None,
):
[docs]
self.database_name = database_name
[docs]
self.table_name = table_name
[docs]
self.expression = expression
[docs]
self.waiter_delay = waiter_delay
[docs]
self.aws_conn_id = aws_conn_id
[docs]
self.region_name = region_name
[docs]
self.botocore_config = botocore_config
[docs]
def serialize(self) -> tuple[str, dict[str, Any]]:
return (
# dynamically generate the fully qualified name of the class
self.__class__.__module__ + "." + self.__class__.__qualname__,
{
"database_name": self.database_name,
"table_name": self.table_name,
"expression": self.expression,
"aws_conn_id": self.aws_conn_id,
"region_name": self.region_name,
"waiter_delay": self.waiter_delay,
"verify": self.verify,
"botocore_config": self.botocore_config,
},
)
@cached_property
[docs]
def hook(self) -> GlueCatalogHook:
return GlueCatalogHook(
aws_conn_id=self.aws_conn_id,
region_name=self.region_name,
verify=self.verify,
config=self.botocore_config,
)
[docs]
async def poke(self, client: Any) -> bool:
if "." in self.table_name:
self.database_name, self.table_name = self.table_name.split(".")
self.log.info(
"Poking for table %s. %s, expression %s", self.database_name, self.table_name, self.expression
)
partitions = await self.hook.async_get_partitions(
client=client,
database_name=self.database_name,
table_name=self.table_name,
expression=self.expression,
)
return bool(partitions)
[docs]
async def run(self) -> AsyncIterator[TriggerEvent]:
async with await self.hook.get_async_conn() as client:
while True:
result = await self.poke(client=client)
if result:
yield TriggerEvent({"status": "success"})
break
else:
await asyncio.sleep(self.waiter_delay)
[docs]
class GlueDataQualityRuleSetEvaluationRunCompleteTrigger(AwsBaseWaiterTrigger):
"""
Trigger when a AWS Glue data quality evaluation run complete.
:param evaluation_run_id: The AWS Glue data quality ruleset evaluation run identifier.
:param waiter_delay: The amount of time in seconds to wait between attempts. (default: 60)
:param waiter_max_attempts: The maximum number of attempts to be made. (default: 75)
:param aws_conn_id: The Airflow connection used for AWS credentials.
"""
def __init__(
self,
evaluation_run_id: str,
waiter_delay: int = 60,
waiter_max_attempts: int = 75,
aws_conn_id: str | None = "aws_default",
):
super().__init__(
serialized_fields={"evaluation_run_id": evaluation_run_id},
waiter_name="data_quality_ruleset_evaluation_run_complete",
waiter_args={"RunId": evaluation_run_id},
failure_message="AWS Glue data quality ruleset evaluation run failed.",
status_message="Status of AWS Glue data quality ruleset evaluation run is",
status_queries=["Status"],
return_key="evaluation_run_id",
return_value=evaluation_run_id,
waiter_delay=waiter_delay,
waiter_max_attempts=waiter_max_attempts,
aws_conn_id=aws_conn_id,
)
[docs]
def hook(self) -> AwsGenericHook:
return GlueDataQualityHook(aws_conn_id=self.aws_conn_id)
[docs]
class GlueDataQualityRuleRecommendationRunCompleteTrigger(AwsBaseWaiterTrigger):
"""
Trigger when a AWS Glue data quality recommendation run complete.
:param recommendation_run_id: The AWS Glue data quality rule recommendation run identifier.
:param waiter_delay: The amount of time in seconds to wait between attempts. (default: 60)
:param waiter_max_attempts: The maximum number of attempts to be made. (default: 75)
:param aws_conn_id: The Airflow connection used for AWS credentials.
"""
def __init__(
self,
recommendation_run_id: str,
waiter_delay: int = 60,
waiter_max_attempts: int = 75,
aws_conn_id: str | None = "aws_default",
):
super().__init__(
serialized_fields={"recommendation_run_id": recommendation_run_id},
waiter_name="data_quality_rule_recommendation_run_complete",
waiter_args={"RunId": recommendation_run_id},
failure_message="AWS Glue data quality recommendation run failed.",
status_message="Status of AWS Glue data quality recommendation run is",
status_queries=["Status"],
return_key="recommendation_run_id",
return_value=recommendation_run_id,
waiter_delay=waiter_delay,
waiter_max_attempts=waiter_max_attempts,
aws_conn_id=aws_conn_id,
)
[docs]
def hook(self) -> AwsGenericHook:
return GlueDataQualityHook(aws_conn_id=self.aws_conn_id)