You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by GitBox <gi...@apache.org> on 2022/07/29 18:11:10 UTC

[GitHub] [airflow] vincbeck commented on a diff in pull request #25324: Add EMR Serverless Operators and Hooks

vincbeck commented on code in PR #25324:
URL: https://github.com/apache/airflow/pull/25324#discussion_r933507751


##########
docs/apache-airflow-providers-amazon/operators/emr_serverless.rst:
##########
@@ -0,0 +1,111 @@
+ .. 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.
+
+
+===============================
+Amazon EMR Serverless Operators
+===============================
+
+`Amazon EMR Serverless <https://aws.amazon.com/emr/serverless/>`__ is a serverless option
+in Amazon EMR that makes it easy for data analysts and engineers to run open-source big
+data analytics frameworks without configuring, managing, and scaling clusters or servers.
+You get all the features and benefits of Amazon EMR without the need for experts to plan
+and manage clusters.
+
+Prerequisite Tasks
+------------------
+
+.. include:: _partials/prerequisite_tasks.rst
+

Review Comment:
   ```suggestion
   Operators
   ---------
   ```



##########
airflow/providers/amazon/aws/sensors/emr.py:
##########
@@ -111,6 +116,152 @@ def failure_message_from_response(response: Dict[str, Any]) -> Optional[str]:
         raise NotImplementedError('Please implement failure_message_from_response() in subclass')
 
 
+class EmrServerlessJobSensor(BaseSensorOperator):
+    """
+    Asks for the state of the job run until it reaches a failure state or success state.
+    If the job run fails, the task will fail.
+
+    .. seealso::
+        For more information on how to use this sensor, take a look at the guide:
+        :ref:`howto/sensor:EmrServerlessJobSensor`
+
+    :param application_id: application_id to check the state of
+    :param job_run_id: job_run_id to check the state of
+    :param target_states: a set of states to wait for, defaults to SUCCESS_STATES
+    :param aws_conn_id: aws connection to use, defaults to 'aws_default'
+    :param emr_conn_id: emr connection to use, defaults to 'emr_default'
+    """
+
+    INTERMEDIATE_STATES = {'PENDING', 'RUNNING', 'SCHEDULED', 'SUBMITTED'}
+    FAILURE_STATES = {'FAILED', 'CANCELLING', 'CANCELLED'}
+    SUCCESS_STATES = {'SUCCESS'}
+    TERMINAL_STATES = SUCCESS_STATES.union(FAILURE_STATES)
+
+    template_fields: Sequence[str] = (
+        'application_id',
+        'job_run_id',
+    )
+
+    def __init__(
+        self,
+        *,
+        application_id: str,
+        job_run_id: str,
+        target_states: Union[Set, FrozenSet] = frozenset(SUCCESS_STATES),
+        aws_conn_id: str = 'aws_default',
+        emr_conn_id: str = 'emr_default',
+        **kwargs: Any,
+    ) -> None:
+        self.aws_conn_id = aws_conn_id
+        self.emr_conn_id = emr_conn_id
+        self.target_states = target_states
+        self.application_id = application_id
+        self.job_run_id = job_run_id
+        super().__init__(**kwargs)
+
+    def poke(self, context: 'Context') -> bool:
+        state = None
+
+        try:
+            response = self.hook.conn.get_job_run(applicationId=self.application_id, jobRunId=self.job_run_id)
+        except Exception:

Review Comment:
   Overall question. Do we want or is there any value converting the `Exception` to `AirflowException`? I can see there is a lot of operators which do not do that. If there is no value, I would rather not doing the conversion just for the sake of having a code cleaner



##########
airflow/providers/amazon/aws/hooks/emr.py:
##########
@@ -90,6 +91,78 @@ def create_job_flow(self, job_flow_overrides: Dict[str, Any]) -> Dict[str, Any]:
         return response
 
 
+class EmrServerlessHook(AwsBaseHook):
+    """
+    Interact with EMR Serverless API.
+
+    Additional arguments (such as ``aws_conn_id``) may be specified and
+    are passed down to the underlying AwsBaseHook.
+
+    .. seealso::
+        :class:`~airflow.providers.amazon.aws.hooks.base_aws.AwsBaseHook`
+    """
+
+    def __init__(self, *args: Any, **kwargs: Any) -> None:
+        kwargs["client_type"] = "emr-serverless"
+        super().__init__(*args, **kwargs)
+
+    @cached_property
+    def conn(self):
+        """Get the underlying boto3 EmrServerlessAPIService client (cached)"""
+        return super().conn
+
+    # This method should be replaced with boto waiters which would implement timeouts and backoff nicely.
+    def waiter(
+        self,
+        get_state_callable: Callable,
+        get_state_args: Dict,
+        parse_response: List,
+        desired_state: Set,
+        failure_states: Set,
+        object_type: str,
+        action: str,
+        countdown: int = 25 * 60,
+        check_interval_seconds: int = 60,
+    ) -> None:
+        """
+        Will run the sensor until it turns True.
+
+        :param get_state_callable: A callable to run until it returns True
+        :param get_state_args: Arguments to pass to get_state_callable
+        :param parse_response: Dictionary keys to extract state from response of get_state_callable
+        :param desired_state: Wait until the getter returns this value
+        :param failure_states: A set of states which indicate failure and should throw an
+        exception if any are reached before the desired_state
+        :param object_type: Used for the reporting string. What are you waiting for? (application, job, etc)
+        :param action: Used for the reporting string. What action are you waiting for? (created, deleted, etc)
+        :param countdown: Total amount of time the waiter should wait for the desired state
+        before timing out (in seconds). Defaults to 25 * 60 seconds.
+        :param check_interval_seconds: Number of seconds waiter should wait before attempting
+        to retry get_state_callable. Defaults to 60 seconds.
+        """
+        response = get_state_callable(**get_state_args)
+        state: str = self.get_state(response, parse_response)
+        while state not in desired_state:
+            if state in failure_states:
+                raise AirflowException(f'{object_type.title()} reached failure state {state}.')
+            if countdown >= check_interval_seconds:
+                countdown -= check_interval_seconds
+                print(f'Waiting for {object_type.lower()} to be {action.lower()}.')
+                sleep(check_interval_seconds)
+                state = self.get_state(get_state_callable(**get_state_args), parse_response)
+            else:
+                message = f'{object_type.title()} still not {action.lower()} after the allocated time limit.'
+                print(message)

Review Comment:
   Same here I guess :)



##########
airflow/providers/amazon/aws/sensors/emr.py:
##########
@@ -111,6 +116,152 @@ def failure_message_from_response(response: Dict[str, Any]) -> Optional[str]:
         raise NotImplementedError('Please implement failure_message_from_response() in subclass')
 
 
+class EmrServerlessJobSensor(BaseSensorOperator):
+    """
+    Asks for the state of the job run until it reaches a failure state or success state.
+    If the job run fails, the task will fail.
+
+    .. seealso::
+        For more information on how to use this sensor, take a look at the guide:
+        :ref:`howto/sensor:EmrServerlessJobSensor`
+
+    :param application_id: application_id to check the state of
+    :param job_run_id: job_run_id to check the state of
+    :param target_states: a set of states to wait for, defaults to SUCCESS_STATES
+    :param aws_conn_id: aws connection to use, defaults to 'aws_default'
+    :param emr_conn_id: emr connection to use, defaults to 'emr_default'
+    """
+
+    INTERMEDIATE_STATES = {'PENDING', 'RUNNING', 'SCHEDULED', 'SUBMITTED'}
+    FAILURE_STATES = {'FAILED', 'CANCELLING', 'CANCELLED'}
+    SUCCESS_STATES = {'SUCCESS'}
+    TERMINAL_STATES = SUCCESS_STATES.union(FAILURE_STATES)
+
+    template_fields: Sequence[str] = (
+        'application_id',
+        'job_run_id',
+    )
+
+    def __init__(
+        self,
+        *,
+        application_id: str,
+        job_run_id: str,
+        target_states: Union[Set, FrozenSet] = frozenset(SUCCESS_STATES),
+        aws_conn_id: str = 'aws_default',
+        emr_conn_id: str = 'emr_default',
+        **kwargs: Any,
+    ) -> None:
+        self.aws_conn_id = aws_conn_id
+        self.emr_conn_id = emr_conn_id
+        self.target_states = target_states
+        self.application_id = application_id
+        self.job_run_id = job_run_id
+        super().__init__(**kwargs)
+
+    def poke(self, context: 'Context') -> bool:
+        state = None

Review Comment:
   I dont think this line is needed



##########
docs/apache-airflow-providers-amazon/operators/emr_serverless.rst:
##########
@@ -0,0 +1,111 @@
+ .. 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.
+
+
+===============================
+Amazon EMR Serverless Operators
+===============================
+
+`Amazon EMR Serverless <https://aws.amazon.com/emr/serverless/>`__ is a serverless option
+in Amazon EMR that makes it easy for data analysts and engineers to run open-source big
+data analytics frameworks without configuring, managing, and scaling clusters or servers.
+You get all the features and benefits of Amazon EMR without the need for experts to plan
+and manage clusters.
+
+Prerequisite Tasks
+------------------
+
+.. include:: _partials/prerequisite_tasks.rst
+
+.. _howto/operator:EmrServerlessCreateApplicationOperator:
+
+Create an EMR Serverless Application
+------------------------------------

Review Comment:
   ```suggestion
   ==========================
   ```



##########
airflow/providers/amazon/aws/sensors/emr.py:
##########
@@ -111,6 +116,152 @@ def failure_message_from_response(response: Dict[str, Any]) -> Optional[str]:
         raise NotImplementedError('Please implement failure_message_from_response() in subclass')
 
 
+class EmrServerlessJobSensor(BaseSensorOperator):
+    """
+    Asks for the state of the job run until it reaches a failure state or success state.
+    If the job run fails, the task will fail.
+
+    .. seealso::
+        For more information on how to use this sensor, take a look at the guide:
+        :ref:`howto/sensor:EmrServerlessJobSensor`
+
+    :param application_id: application_id to check the state of
+    :param job_run_id: job_run_id to check the state of
+    :param target_states: a set of states to wait for, defaults to SUCCESS_STATES
+    :param aws_conn_id: aws connection to use, defaults to 'aws_default'
+    :param emr_conn_id: emr connection to use, defaults to 'emr_default'
+    """
+
+    INTERMEDIATE_STATES = {'PENDING', 'RUNNING', 'SCHEDULED', 'SUBMITTED'}
+    FAILURE_STATES = {'FAILED', 'CANCELLING', 'CANCELLED'}
+    SUCCESS_STATES = {'SUCCESS'}
+    TERMINAL_STATES = SUCCESS_STATES.union(FAILURE_STATES)
+
+    template_fields: Sequence[str] = (
+        'application_id',
+        'job_run_id',
+    )
+
+    def __init__(
+        self,
+        *,
+        application_id: str,
+        job_run_id: str,
+        target_states: Union[Set, FrozenSet] = frozenset(SUCCESS_STATES),
+        aws_conn_id: str = 'aws_default',
+        emr_conn_id: str = 'emr_default',
+        **kwargs: Any,
+    ) -> None:
+        self.aws_conn_id = aws_conn_id
+        self.emr_conn_id = emr_conn_id
+        self.target_states = target_states
+        self.application_id = application_id
+        self.job_run_id = job_run_id
+        super().__init__(**kwargs)
+
+    def poke(self, context: 'Context') -> bool:
+        state = None
+
+        try:
+            response = self.hook.conn.get_job_run(applicationId=self.application_id, jobRunId=self.job_run_id)
+        except Exception:
+            raise AirflowException(f'Unable to get job state: {response}')
+
+        state = response['jobRun']['state']
+
+        if state in self.FAILURE_STATES:
+            failure_message = f"EMR Serverless job failed: {self.failure_message_from_response(response)}"
+            raise AirflowException(failure_message)
+
+        return state in self.target_states
+
+    @cached_property
+    def hook(self) -> EmrServerlessHook:
+        """Create and return an EmrServerlessHook"""
+        return EmrServerlessHook()

Review Comment:
   Agree, we should pass `aws_conn_id`



##########
airflow/providers/amazon/aws/sensors/emr.py:
##########
@@ -111,6 +116,152 @@ def failure_message_from_response(response: Dict[str, Any]) -> Optional[str]:
         raise NotImplementedError('Please implement failure_message_from_response() in subclass')
 
 
+class EmrServerlessJobSensor(BaseSensorOperator):
+    """
+    Asks for the state of the job run until it reaches a failure state or success state.
+    If the job run fails, the task will fail.
+
+    .. seealso::
+        For more information on how to use this sensor, take a look at the guide:
+        :ref:`howto/sensor:EmrServerlessJobSensor`
+
+    :param application_id: application_id to check the state of
+    :param job_run_id: job_run_id to check the state of
+    :param target_states: a set of states to wait for, defaults to SUCCESS_STATES
+    :param aws_conn_id: aws connection to use, defaults to 'aws_default'
+    :param emr_conn_id: emr connection to use, defaults to 'emr_default'
+    """
+
+    INTERMEDIATE_STATES = {'PENDING', 'RUNNING', 'SCHEDULED', 'SUBMITTED'}
+    FAILURE_STATES = {'FAILED', 'CANCELLING', 'CANCELLED'}
+    SUCCESS_STATES = {'SUCCESS'}
+    TERMINAL_STATES = SUCCESS_STATES.union(FAILURE_STATES)
+
+    template_fields: Sequence[str] = (
+        'application_id',
+        'job_run_id',
+    )
+
+    def __init__(
+        self,
+        *,
+        application_id: str,
+        job_run_id: str,
+        target_states: Union[Set, FrozenSet] = frozenset(SUCCESS_STATES),
+        aws_conn_id: str = 'aws_default',
+        emr_conn_id: str = 'emr_default',
+        **kwargs: Any,
+    ) -> None:
+        self.aws_conn_id = aws_conn_id
+        self.emr_conn_id = emr_conn_id

Review Comment:
   I agree. It seems `emr_conn_id` is not used. You can just remove it



##########
airflow/providers/amazon/aws/sensors/emr.py:
##########
@@ -111,6 +116,152 @@ def failure_message_from_response(response: Dict[str, Any]) -> Optional[str]:
         raise NotImplementedError('Please implement failure_message_from_response() in subclass')
 
 
+class EmrServerlessJobSensor(BaseSensorOperator):
+    """
+    Asks for the state of the job run until it reaches a failure state or success state.
+    If the job run fails, the task will fail.
+
+    .. seealso::
+        For more information on how to use this sensor, take a look at the guide:
+        :ref:`howto/sensor:EmrServerlessJobSensor`
+
+    :param application_id: application_id to check the state of
+    :param job_run_id: job_run_id to check the state of
+    :param target_states: a set of states to wait for, defaults to SUCCESS_STATES

Review Comment:
   Agree



-- 
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-unsubscribe@airflow.apache.org

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