ROOBALJINDAL commented on issue #67178:
URL: https://github.com/apache/airflow/issues/67178#issuecomment-4497520838
@eladkal @Subham-KRLX
We tried creating custom implementation of EmrServerlessStartJobOperator
with patched waiter_with_logging.py and still issue is reproducible. We
confirmed that modified waiter_with_logging.py is in use, we added some custom
loggers, those were printed in other successful airflow tasks
Following is the code we did, please let us know if we missed something
**emr_serverless_operator.py**
```
# Backport workaround for EmrServerlessStartJobOperator.
#
# The upstream `wait` in
airflow.providers.amazon.aws.utils.waiter_with_logging
# has a bug that causes the operator task to be killed within ~20s. This
# subclass overrides execute() with the verbatim body from
# apache-airflow-providers-amazon 9.12.0 and routes the wait() call through
# our locally backported waiter_with_logging module.
#
# Remove this subclass (and waiter_with_logging.py) once the deployment is
# upgraded to a provider version that contains the upstream fix.
from __future__ import annotations
from datetime import timedelta
from typing import TYPE_CHECKING, Any
from uuid import uuid4
from airflow.exceptions import AirflowException
from airflow.providers.amazon.aws.hooks.emr import EmrServerlessHook
from airflow.providers.amazon.aws.operators.emr import
EmrServerlessStartJobOperator
from airflow.providers.amazon.aws.triggers.emr import (
EmrServerlessStartApplicationTrigger,
EmrServerlessStartJobTrigger,
)
from waiter_with_logging import wait
if TYPE_CHECKING:
from airflow.utils.context import Context
class MyEmrServerlessStartJobOperator(EmrServerlessStartJobOperator):
"""EmrServerlessStartJobOperator that uses the backported wait()."""
def execute(self, context: Context, event: dict[str, Any] | None = None)
-> str | None:
app_state =
self.hook.conn.get_application(applicationId=self.application_id)["application"]["state"]
if app_state not in EmrServerlessHook.APPLICATION_SUCCESS_STATES:
self.log.info("Application state is %s", app_state)
self.log.info("Starting application %s", self.application_id)
self.hook.conn.start_application(applicationId=self.application_id)
waiter = self.hook.get_waiter("serverless_app_started")
if self.deferrable:
self.defer(
trigger=EmrServerlessStartApplicationTrigger(
application_id=self.application_id,
waiter_delay=self.waiter_delay,
waiter_max_attempts=self.waiter_max_attempts,
aws_conn_id=self.aws_conn_id,
),
method_name="execute",
timeout=timedelta(seconds=self.waiter_max_attempts *
self.waiter_delay),
)
wait(
waiter=waiter,
waiter_max_attempts=self.waiter_max_attempts,
waiter_delay=self.waiter_delay,
args={"applicationId": self.application_id},
failure_message="Serverless Application failed to start",
status_message="Serverless Application status is",
status_args=["application.state",
"application.stateDetails"],
)
self.log.info("Starting job on Application: %s", self.application_id)
self.name = self.name or self.config.pop("name",
f"emr_serverless_job_airflow_{uuid4()}")
args = {
"clientToken": self.client_request_token,
"applicationId": self.application_id,
"executionRoleArn": self.execution_role_arn,
"jobDriver": self.job_driver,
"name": self.name,
**self.config,
}
if self.configuration_overrides is not None:
args["configurationOverrides"] = self.configuration_overrides
response = self.hook.conn.start_job_run(
**args,
)
if response["ResponseMetadata"]["HTTPStatusCode"] != 200:
raise AirflowException(f"EMR serverless job failed to start:
{response}")
self.job_id = response["jobRunId"]
self.log.info("EMR serverless job started: %s", self.job_id)
self.persist_links(context)
if self.wait_for_completion:
if self.deferrable:
self.defer(
trigger=EmrServerlessStartJobTrigger(
application_id=self.application_id,
job_id=self.job_id,
waiter_delay=self.waiter_delay,
waiter_max_attempts=self.waiter_max_attempts,
aws_conn_id=self.aws_conn_id,
),
method_name="execute_complete",
timeout=timedelta(seconds=self.waiter_max_attempts *
self.waiter_delay),
)
else:
waiter = self.hook.get_waiter("serverless_job_completed")
wait(
waiter=waiter,
waiter_max_attempts=self.waiter_max_attempts,
waiter_delay=self.waiter_delay,
args={"applicationId": self.application_id, "jobRunId":
self.job_id},
failure_message="Serverless Job failed",
status_message="Serverless Job status is",
status_args=["jobRun.state", "jobRun.stateDetails"],
)
return self.job_id
```
**waiter_with_logging.py**
```
# 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.
# Backport of the patched waiter_with_logging from apache/airflow PR
# (fix for EmrServerlessStartJobOperator task being killed within ~20s).
# Remove once apache-airflow-providers-amazon ships the fix and the
# deployment is upgraded.
from __future__ import annotations
import asyncio
import logging
import time
from typing import TYPE_CHECKING, Any
import jmespath
from botocore.exceptions import NoCredentialsError, WaiterError
from airflow.exceptions import AirflowException
if TYPE_CHECKING:
from botocore.waiter import Waiter
# Standard throttling and transient error codes to retry on
# https://docs.aws.amazon.com/general/latest/gr/api-retries.html
# and
https://github.com/boto/botocore/blob/e25e9be5ea42a1eb5097f48b11c977d4c38d5c4b/botocore/retryhandler.py
RETRIABLE_ERROR_CODES = {
"ThrottlingException",
"Throttling",
"RequestLimitExceeded",
"ProvisionedThroughputExceededException",
"LimitExceededException",
"RequestThrottled",
"RequestThrottledException",
"TooManyRequestsException",
"ServerException",
"InternalServerError",
"InternalFailure",
"ServiceUnavailable",
"BadGateway",
"GatewayTimeout",
"RequestTimeout",
"RequestTimeoutException",
}
def wait(
waiter: Waiter,
waiter_delay: int,
waiter_max_attempts: int,
args: dict[str, Any],
failure_message: str,
status_message: str,
status_args: list[str],
) -> None:
"""
Use a boto waiter to poll an AWS service for the specified state.
Although this function uses boto waiters to poll the state of the
service, it logs the response of the service after every attempt,
which is not currently supported by boto waiters.
:param waiter: The boto waiter to use.
:param waiter_delay: The amount of time in seconds to wait between
attempts.
:param waiter_max_attempts: The maximum number of attempts to be made.
:param args: The arguments to pass to the waiter.
:param failure_message: The message to log if a failure state is reached.
:param status_message: The message logged when printing the status of
the service.
:param status_args: A list containing the JMESPath queries to retrieve
status information from
the waiter response.
e.g.
response = {"Cluster": {"state": "CREATING"}}
status_args = ["Cluster.state"]
response = {
"Clusters": [{"state": "CREATING", "details": "User initiated."},]
}
status_args = ["Clusters[0].state", "Clusters[0].details"]
"""
log = logging.getLogger(__name__)
for attempt in range(waiter_max_attempts):
if attempt:
time.sleep(waiter_delay)
try:
waiter.wait(**args, WaiterConfig={"MaxAttempts": 1})
except NoCredentialsError as error:
log.info(str(error))
except WaiterError as error:
error_reason = str(error)
last_response = error.last_response
if "terminal failure" in error_reason:
log.error("%s: %s", failure_message,
_LazyStatusFormatter(status_args, last_response))
raise AirflowException(f"{failure_message}: {error}")
if (
"An error occurred" in error_reason
and isinstance(last_response.get("Error"), dict)
and "Code" in last_response.get("Error")
):
error_code = last_response["Error"]["Code"]
if error_code not in RETRIABLE_ERROR_CODES:
raise AirflowException(f"{failure_message}: {error}")
log.info("Waiter encountered retriable error: %s.
Retrying...", error_code)
log.info("%s: %s", status_message,
_LazyStatusFormatter(status_args, last_response))
else:
break
else:
raise AirflowException("Waiter error: max attempts reached")
async def async_wait(
waiter: Waiter,
waiter_delay: int,
waiter_max_attempts: int,
args: dict[str, Any],
failure_message: str,
status_message: str,
status_args: list[str],
):
"""
Use an async boto waiter to poll an AWS service for the specified state.
Although this function uses boto waiters to poll the state of the
service, it logs the response of the service after every attempt,
which is not currently supported by boto waiters.
:param waiter: The boto waiter to use.
:param waiter_delay: The amount of time in seconds to wait between
attempts.
:param waiter_max_attempts: The maximum number of attempts to be made.
:param args: The arguments to pass to the waiter.
:param failure_message: The message to log if a failure state is reached.
:param status_message: The message logged when printing the status of
the service.
:param status_args: A list containing the JMESPath queries to retrieve
status information from
the waiter response.
e.g.
response = {"Cluster": {"state": "CREATING"}}
status_args = ["Cluster.state"]
response = {
"Clusters": [{"state": "CREATING", "details": "User initiated."},]
}
status_args = ["Clusters[0].state", "Clusters[0].details"]
"""
log = logging.getLogger(__name__)
for attempt in range(waiter_max_attempts):
if attempt:
await asyncio.sleep(waiter_delay)
try:
await waiter.wait(**args, WaiterConfig={"MaxAttempts": 1})
except NoCredentialsError as error:
log.info(str(error))
except WaiterError as error:
error_reason = str(error)
last_response = error.last_response
if "terminal failure" in error_reason:
raise AirflowException(
f"{failure_message}: {_LazyStatusFormatter(status_args,
last_response)}\n{error}"
)
if (
"An error occurred" in error_reason
and isinstance(last_response.get("Error"), dict)
and "Code" in last_response.get("Error")
):
error_code = last_response["Error"]["Code"]
if error_code not in RETRIABLE_ERROR_CODES:
raise
AirflowException(f"{failure_message}\n{last_response}\n{error}")
log.info("Waiter encountered retriable error: %s.
Retrying...", error_code)
log.info("%s: %s", status_message,
_LazyStatusFormatter(status_args, last_response))
else:
break
else:
raise AirflowException("Waiter error: max attempts reached")
class _LazyStatusFormatter:
"""
Contains the info necessary to extract the status from a response; only
computes the value when necessary.
Used to avoid computations if the logs are disabled at the given level.
"""
def __init__(self, jmespath_queries: list[str], response: dict[str,
Any]):
self.jmespath_queries = jmespath_queries
self.response = response
def __str__(self):
"""Loop through the args list and generate a string containing
values from the waiter response."""
values = []
for query in self.jmespath_queries:
value = jmespath.search(query, self.response)
if value is not None and value != "":
values.append(str(value))
return " - ".join(values)
```
--
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]