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/12/12 19:16:05 UTC

[GitHub] [airflow] syedahsn opened a new pull request, #28312: EMR Notebook operator

syedahsn opened a new pull request, #28312:
URL: https://github.com/apache/airflow/pull/28312

   This PR introduces 2 new EMR Operators `EmrStartNotebookExecutionOperator` and `EmrStopNotebookExecutionOperator` to control the execution of notebooks in an EMR cluster. The PR also includes a sensor to check the state of the notebook execution, as well as unit tests for all new operators and sensors. The PR also includes a system test to show the functionality of the operators and sensors.
   <!--
   Thank you for contributing! Please make sure that your code changes
   are covered with tests. And in case of new features or big changes
   remember to adjust the documentation.
   
   Feel free to ping committers for the review!
   
   In case of an existing issue, reference it using one of the following:
   
   closes: #ISSUE
   related: #ISSUE
   
   How to write a good git commit message:
   http://chris.beams.io/posts/git-commit/
   -->
   
   ---
   **^ Add meaningful description above**
   
   Read the **[Pull Request Guidelines](https://github.com/apache/airflow/blob/main/CONTRIBUTING.rst#pull-request-guidelines)** for more information.
   In case of fundamental code changes, an Airflow Improvement Proposal ([AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvement+Proposals)) is needed.
   In case of a new dependency, check compliance with the [ASF 3rd Party License Policy](https://www.apache.org/legal/resolved.html#category-x).
   In case of backwards incompatible changes please leave a note in a newsfragment file, named `{pr_number}.significant.rst` or `{issue_number}.significant.rst`, in [newsfragments](https://github.com/apache/airflow/tree/main/newsfragments).
   


-- 
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


[GitHub] [airflow] syedahsn commented on a diff in pull request #28312: EMR Notebook operator

Posted by GitBox <gi...@apache.org>.
syedahsn commented on code in PR #28312:
URL: https://github.com/apache/airflow/pull/28312#discussion_r1046405613


##########
tests/providers/amazon/aws/sensors/test_emr_notebook_execution.py:
##########
@@ -0,0 +1,77 @@
+#
+# 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
+
+from typing import Any
+from unittest import mock
+
+import pytest
+
+from airflow.exceptions import AirflowException
+from airflow.providers.amazon.aws.sensors.emr import EmrNotebookExecutionSensor
+
+
+class TestEmrNotebookExecutionSensor:
+    def _generate_response(self, status: str, reason: str | None = None) -> dict[str, Any]:
+        return {
+            "NotebookExecution": {
+                "Status": status,
+                "LastStateChangeReason": reason,
+            },
+            "ResponseMetadata": {
+                "HTTPStatusCode": 200,
+            },
+        }
+
+    @mock.patch("airflow.providers.amazon.aws.hooks.emr.EmrHook.conn")
+    def test_emr_notebook_execution_sensor_success_state(self, mock_conn):
+        mock_conn.describe_notebook_execution.return_value = self._generate_response("FINISHED")
+        sensor = EmrNotebookExecutionSensor(
+            task_id="test_task",
+            poke_interval=0,
+            notebook_execution_id="test-execution-id",
+        )
+        sensor.poke(None)
+        mock_conn.describe_notebook_execution.assert_called_once_with(NotebookExecutionId="test-execution-id")
+
+    @mock.patch("airflow.providers.amazon.aws.hooks.emr.EmrHook.conn")
+    def test_emr_notebook_execution_sensor_failed_state(self, mock_conn):
+        error_reason = "Test error"
+        mock_conn.describe_notebook_execution.return_value = self._generate_response("FAILED", error_reason)
+        sensor = EmrNotebookExecutionSensor(
+            task_id="test_task",
+            poke_interval=0,
+            notebook_execution_id="test-execution-id",
+        )
+        with pytest.raises(AirflowException) as ex_message:
+            sensor.poke(None)
+        mock_conn.describe_notebook_execution.assert_called_once_with(NotebookExecutionId="test-execution-id")
+        assert str(ex_message.value) == "EMR job failed " + error_reason

Review Comment:
   Nice, I didn't know I could do that. Thanks!



-- 
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


[GitHub] [airflow] syedahsn commented on pull request #28312: EMR Notebook operator

Posted by GitBox <gi...@apache.org>.
syedahsn commented on PR #28312:
URL: https://github.com/apache/airflow/pull/28312#issuecomment-1353594343

   @Taragolis Can you take a look at this PR again when you have time? Thanks!


-- 
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


[GitHub] [airflow] potiuk merged pull request #28312: EMR Notebook operator

Posted by GitBox <gi...@apache.org>.
potiuk merged PR #28312:
URL: https://github.com/apache/airflow/pull/28312


-- 
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


[GitHub] [airflow] Taragolis commented on a diff in pull request #28312: EMR Notebook operator

Posted by GitBox <gi...@apache.org>.
Taragolis commented on code in PR #28312:
URL: https://github.com/apache/airflow/pull/28312#discussion_r1046367557


##########
tests/providers/amazon/aws/sensors/test_emr_notebook_execution.py:
##########
@@ -0,0 +1,77 @@
+#
+# 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
+
+from typing import Any
+from unittest import mock
+
+import pytest
+
+from airflow.exceptions import AirflowException
+from airflow.providers.amazon.aws.sensors.emr import EmrNotebookExecutionSensor
+
+
+class TestEmrNotebookExecutionSensor:
+    def _generate_response(self, status: str, reason: str | None = None) -> dict[str, Any]:
+        return {
+            "NotebookExecution": {
+                "Status": status,
+                "LastStateChangeReason": reason,
+            },
+            "ResponseMetadata": {
+                "HTTPStatusCode": 200,
+            },
+        }
+
+    @mock.patch("airflow.providers.amazon.aws.hooks.emr.EmrHook.conn")
+    def test_emr_notebook_execution_sensor_success_state(self, mock_conn):
+        mock_conn.describe_notebook_execution.return_value = self._generate_response("FINISHED")
+        sensor = EmrNotebookExecutionSensor(
+            task_id="test_task",
+            poke_interval=0,
+            notebook_execution_id="test-execution-id",
+        )
+        sensor.poke(None)
+        mock_conn.describe_notebook_execution.assert_called_once_with(NotebookExecutionId="test-execution-id")
+
+    @mock.patch("airflow.providers.amazon.aws.hooks.emr.EmrHook.conn")
+    def test_emr_notebook_execution_sensor_failed_state(self, mock_conn):
+        error_reason = "Test error"
+        mock_conn.describe_notebook_execution.return_value = self._generate_response("FAILED", error_reason)
+        sensor = EmrNotebookExecutionSensor(
+            task_id="test_task",
+            poke_interval=0,
+            notebook_execution_id="test-execution-id",
+        )
+        with pytest.raises(AirflowException) as ex_message:
+            sensor.poke(None)
+        mock_conn.describe_notebook_execution.assert_called_once_with(NotebookExecutionId="test-execution-id")
+        assert str(ex_message.value) == "EMR job failed " + error_reason

Review Comment:
   You could validate exception message within [pytest.raises](https://docs.pytest.org/en/7.1.x/how-to/assert.html#assertions-about-expected-exceptions)
   ```suggestion
           with pytest.raises(AirflowException, match=fr"EMR job failed: {error_reason}"):
               sensor.poke(None)
           mock_conn.describe_notebook_execution.assert_called_once_with(NotebookExecutionId="test-execution-id")
   ```



##########
tests/providers/amazon/aws/operators/test_emr_notebook.py:
##########
@@ -0,0 +1,293 @@
+#
+# 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
+
+from unittest import mock
+
+import pytest
+
+from airflow.exceptions import AirflowException
+from airflow.providers.amazon.aws.operators.emr import (
+    EmrStartNotebookExecutionOperator,
+    EmrStopNotebookExecutionOperator,
+)
+
+PARAMS = {
+    "EditorId": "test_editor",
+    "RelativePath": "test_relative_path",
+    "ServiceRole": "test_role",
+    "NotebookExecutionName": "test_name",
+    "NotebookParams": "test_params",
+    "NotebookInstanceSecurityGroupId": "test_notebook_instance_security_group_id",
+    "Tags": [{"test_key": "test_value"}],
+    "ExecutionEngine": {
+        "Id": "test_cluster_id",
+        "Type": "EMR",
+        "MasterInstanceSecurityGroupId": "test_master_instance_security_group_id",
+    },
+}
+
+
+class TestEmrStartNotebookExecutionOperator:
+    @mock.patch("airflow.providers.amazon.aws.hooks.emr.EmrHook.conn")
+    def test_start_notebook_execution_wait_for_completion(self, mock_conn):
+        test_execution_id = "test-execution-id"
+        mock_conn.start_notebook_execution.return_value = {
+            "NotebookExecutionId": test_execution_id,
+            "ResponseMetadata": {
+                "HTTPStatusCode": 200,
+            },
+        }
+        mock_conn.describe_notebook_execution.return_value = {"NotebookExecution": {"Status": "FINISHED"}}
+
+        op = EmrStartNotebookExecutionOperator(
+            task_id="test-id",
+            editor_id=PARAMS["EditorId"],
+            relative_path=PARAMS["RelativePath"],
+            cluster_id=PARAMS["ExecutionEngine"]["Id"],
+            service_role=PARAMS["ServiceRole"],
+            notebook_execution_name=PARAMS["NotebookExecutionName"],
+            notebook_params=PARAMS["NotebookParams"],
+            notebook_instance_security_group_id=PARAMS["NotebookInstanceSecurityGroupId"],
+            master_instance_security_group_id=PARAMS["ExecutionEngine"]["MasterInstanceSecurityGroupId"],
+            tags=PARAMS["Tags"],
+            wait_for_completion=True,
+        )
+        op_response = op.execute(None)
+
+        mock_conn.start_notebook_execution.assert_called_once_with(**PARAMS)
+        mock_conn.describe_notebook_execution.assert_called_once_with(NotebookExecutionId=test_execution_id)
+        assert op_response == test_execution_id
+
+    @mock.patch("airflow.providers.amazon.aws.hooks.emr.EmrHook.conn")
+    def test_start_notebook_execution_no_wait_for_completion(self, mock_conn):
+        test_execution_id = "test-execution-id"
+        mock_conn.start_notebook_execution.return_value = {
+            "NotebookExecutionId": test_execution_id,
+            "ResponseMetadata": {
+                "HTTPStatusCode": 200,
+            },
+        }
+
+        op = EmrStartNotebookExecutionOperator(
+            task_id="test-id",
+            editor_id=PARAMS["EditorId"],
+            relative_path=PARAMS["RelativePath"],
+            cluster_id=PARAMS["ExecutionEngine"]["Id"],
+            service_role=PARAMS["ServiceRole"],
+            notebook_execution_name=PARAMS["NotebookExecutionName"],
+            notebook_params=PARAMS["NotebookParams"],
+            notebook_instance_security_group_id=PARAMS["NotebookInstanceSecurityGroupId"],
+            master_instance_security_group_id=PARAMS["ExecutionEngine"]["MasterInstanceSecurityGroupId"],
+            tags=PARAMS["Tags"],
+        )
+        op_response = op.execute(None)
+
+        mock_conn.start_notebook_execution.assert_called_once_with(**PARAMS)
+        assert op.wait_for_completion is False
+        assert not mock_conn.describe_notebook_execution.called
+        assert op_response == test_execution_id
+
+    @mock.patch("airflow.providers.amazon.aws.hooks.emr.EmrHook.conn")
+    def test_start_notebook_execution_http_code_fail(self, mock_conn):
+        test_execution_id = "test-execution-id"
+        mock_conn.start_notebook_execution.return_value = {
+            "NotebookExecutionId": test_execution_id,
+            "ResponseMetadata": {
+                "HTTPStatusCode": 400,
+            },
+        }
+        op = EmrStartNotebookExecutionOperator(
+            task_id="test-id",
+            editor_id=PARAMS["EditorId"],
+            relative_path=PARAMS["RelativePath"],
+            cluster_id=PARAMS["ExecutionEngine"]["Id"],
+            service_role=PARAMS["ServiceRole"],
+            notebook_execution_name=PARAMS["NotebookExecutionName"],
+            notebook_params=PARAMS["NotebookParams"],
+            notebook_instance_security_group_id=PARAMS["NotebookInstanceSecurityGroupId"],
+            master_instance_security_group_id=PARAMS["ExecutionEngine"]["MasterInstanceSecurityGroupId"],
+            tags=PARAMS["Tags"],
+        )
+        with pytest.raises(AirflowException) as ex_message:
+            op.execute(None)
+
+        mock_conn.start_notebook_execution.assert_called_once_with(**PARAMS)
+        assert "Starting Notebook execution failed" in str(ex_message.value)
+
+    @mock.patch("time.sleep", return_value=None)
+    @mock.patch("airflow.providers.amazon.aws.hooks.emr.EmrHook.conn")
+    def test_start_notebook_execution_wait_for_completion_multiple_attempts(self, mock_conn, _):
+        test_execution_id = "test-execution-id"
+        mock_conn.start_notebook_execution.return_value = {
+            "NotebookExecutionId": test_execution_id,
+            "ResponseMetadata": {
+                "HTTPStatusCode": 200,
+            },
+        }
+        mock_conn.describe_notebook_execution.side_effect = [
+            {"NotebookExecution": {"Status": "PENDING"}},
+            {"NotebookExecution": {"Status": "PENDING"}},
+            {"NotebookExecution": {"Status": "FINISHED"}},
+        ]
+
+        op = EmrStartNotebookExecutionOperator(
+            task_id="test-id",
+            editor_id=PARAMS["EditorId"],
+            relative_path=PARAMS["RelativePath"],
+            cluster_id=PARAMS["ExecutionEngine"]["Id"],
+            service_role=PARAMS["ServiceRole"],
+            notebook_execution_name=PARAMS["NotebookExecutionName"],
+            notebook_params=PARAMS["NotebookParams"],
+            notebook_instance_security_group_id=PARAMS["NotebookInstanceSecurityGroupId"],
+            master_instance_security_group_id=PARAMS["ExecutionEngine"]["MasterInstanceSecurityGroupId"],
+            tags=PARAMS["Tags"],
+            wait_for_completion=True,
+        )
+        op_response = op.execute(None)
+
+        mock_conn.start_notebook_execution.assert_called_once_with(**PARAMS)
+        mock_conn.describe_notebook_execution.assert_called_with(NotebookExecutionId=test_execution_id)
+        assert mock_conn.describe_notebook_execution.call_count == 3
+        assert op_response == test_execution_id
+
+    @mock.patch("airflow.providers.amazon.aws.hooks.emr.EmrHook.conn")
+    def test_start_notebook_execution_wait_for_completion_fail_state(self, mock_conn):
+        test_execution_id = "test-execution-id"
+        mock_conn.start_notebook_execution.return_value = {
+            "NotebookExecutionId": test_execution_id,
+            "ResponseMetadata": {
+                "HTTPStatusCode": 200,
+            },
+        }
+        mock_conn.describe_notebook_execution.return_value = {"NotebookExecution": {"Status": "FAILED"}}
+
+        op = EmrStartNotebookExecutionOperator(
+            task_id="test-id",
+            editor_id=PARAMS["EditorId"],
+            relative_path=PARAMS["RelativePath"],
+            cluster_id=PARAMS["ExecutionEngine"]["Id"],
+            service_role=PARAMS["ServiceRole"],
+            notebook_execution_name=PARAMS["NotebookExecutionName"],
+            notebook_params=PARAMS["NotebookParams"],
+            notebook_instance_security_group_id=PARAMS["NotebookInstanceSecurityGroupId"],
+            master_instance_security_group_id=PARAMS["ExecutionEngine"]["MasterInstanceSecurityGroupId"],
+            tags=PARAMS["Tags"],
+            wait_for_completion=True,
+        )
+        with pytest.raises(AirflowException) as ex_message:
+            op.execute(None)
+        assert "Notebook Execution reached failure state FAILED." in str(ex_message.value)

Review Comment:
   ```suggestion
           with pytest.raises(AirflowException, match=r"Notebook execution reached failure state FAILED\."):
               op.execute(None)
   ```



-- 
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