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 2020/08/08 19:30:36 UTC

[GitHub] [airflow] potiuk commented on a change in pull request #10246: Added DataprepGetJobsForJobGroupOperator

potiuk commented on a change in pull request #10246:
URL: https://github.com/apache/airflow/pull/10246#discussion_r467495623



##########
File path: airflow/providers/google/cloud/hooks/dataprep.py
##########
@@ -0,0 +1,74 @@
+#
+# 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.
+"""
+This module contains Google Dataprep hook.
+"""
+
+import requests
+from tenacity import retry, stop_after_attempt, wait_exponential
+
+from airflow import AirflowException
+from airflow.hooks.base_hook import BaseHook
+
+
+class GoogleDataprepHook(BaseHook):
+    """
+    Hook for connection with Dataprep API.
+    To get connection Dataprep with Airflow you need Dataprep token.
+    https://clouddataprep.com/documentation/api#section/Authentication
+
+    It should be added to the Connection in Airflow in JSON format.
+
+    """
+
+    def __init__(self, dataprep_conn_id: str = "dataprep_conn_id") -> None:
+        super().__init__()
+        self.dataprep_conn_id = dataprep_conn_id
+        self._url = "https://api.clouddataprep.com/v4/jobGroups"
+
+    @property
+    def _headers(self):

Review comment:
       ```suggestion
       def _headers(self) -> Dict[str, str]:
   ```

##########
File path: tests/providers/google/cloud/hooks/test_dataprep.py
##########
@@ -0,0 +1,97 @@
+#
+# 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 unittest import mock
+
+import pytest
+from mock import patch
+from requests import HTTPError
+from tenacity import RetryError
+
+from airflow.providers.google.cloud.hooks import dataprep
+
+JOB_ID = 1234567
+URL = "https://api.clouddataprep.com/v4/jobGroups"
+TOKEN = "1111"
+EXTRA = {"token": TOKEN}
+
+
+@pytest.fixture(scope="class")
+def mock_hook():
+    with mock.patch("airflow.hooks.base_hook.BaseHook.get_connection") as conn:
+        hook = dataprep.GoogleDataprepHook(dataprep_conn_id="dataprep_conn_id")
+        conn.return_value.extra_dejson = EXTRA
+        yield hook
+
+
+class TestGoogleDataprepHook:
+    def test_get_token(self, mock_hook):
+        assert mock_hook._token == TOKEN
+
+    @patch("airflow.providers.google.cloud.hooks.dataprep.requests.get")
+    def test_mock_should_be_called_once_with_params(self, mock_get_request, mock_hook):
+        mock_hook.get_jobs_for_job_group(job_id=JOB_ID)
+        mock_get_request.assert_called_once_with(
+            f"{URL}/{JOB_ID}/jobs",
+            headers={
+                "Content-Type": "application/json",
+                "Authorization": f"Bearer {TOKEN}",
+            },
+        )
+
+    @patch(
+        "airflow.providers.google.cloud.hooks.dataprep.requests.get",
+        side_effect=[HTTPError(), mock.MagicMock()],
+    )
+    def test_should_pass_after_retry(self, mock_get_request, mock_hook):
+        mock_hook.get_jobs_for_job_group(JOB_ID)
+        assert mock_get_request.call_count == 2
+
+    @patch(
+        "airflow.providers.google.cloud.hooks.dataprep.requests.get",
+        side_effect=[mock.MagicMock(), HTTPError()],
+    )
+    def test_should_not_retry_after_success(self, mock_get_request, mock_hook):
+        mock_hook.get_jobs_for_job_group.retry.sleep = mock.Mock()  # pylint: disable=no-member
+        mock_hook.get_jobs_for_job_group(JOB_ID)
+        assert mock_get_request.call_count == 1
+
+    @patch(
+        "airflow.providers.google.cloud.hooks.dataprep.requests.get",
+        side_effect=[

Review comment:
       Nice test!

##########
File path: docs/howto/operator/google/cloud/dataprep.rst
##########
@@ -0,0 +1,60 @@
+ .. 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.
+
+Google Dataprep Operators
+=======================================

Review comment:
       Too long "underline' (====) -> should be the same length as the text above. 

##########
File path: airflow/providers/google/cloud/hooks/dataprep.py
##########
@@ -0,0 +1,74 @@
+#
+# 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.
+"""
+This module contains Google Dataprep hook.
+"""
+
+import requests
+from tenacity import retry, stop_after_attempt, wait_exponential
+
+from airflow import AirflowException
+from airflow.hooks.base_hook import BaseHook
+
+
+class GoogleDataprepHook(BaseHook):
+    """
+    Hook for connection with Dataprep API.
+    To get connection Dataprep with Airflow you need Dataprep token.
+    https://clouddataprep.com/documentation/api#section/Authentication
+
+    It should be added to the Connection in Airflow in JSON format.
+
+    """
+
+    def __init__(self, dataprep_conn_id: str = "dataprep_conn_id") -> None:
+        super().__init__()
+        self.dataprep_conn_id = dataprep_conn_id
+        self._url = "https://api.clouddataprep.com/v4/jobGroups"
+
+    @property
+    def _headers(self):
+        headers = {
+            "Content-Type": "application/json",
+            "Authorization": f"Bearer {self._token}",
+        }
+        return headers
+
+    @property
+    def _token(self) -> str:
+        conn = self.get_connection(self.dataprep_conn_id)
+        token = conn.extra_dejson.get("token")
+        if token is None:
+            raise AirflowException(
+                "Dataprep token is missing or has invalid format. "
+                "Please make sure that Dataprep token is added to the Airflow Connections."
+            )
+        return token
+
+    @retry(stop=stop_after_attempt(5), wait=wait_exponential(multiplier=1, max=10))
+    def get_jobs_for_job_group(self, job_id: int):
+        """
+        Get information about the batch jobs within a Cloud Dataprep job.
+
+        :param job_id The ID of the job that will be fetched.
+        :type job_id: int
+        """
+        url: str = f"{self._url}/{job_id}/jobs"
+        response = requests.get(url, headers=self._headers)
+        response.raise_for_status()

Review comment:
       Nice! I did not know it existed  :)

##########
File path: tests/providers/google/cloud/hooks/test_dataprep.py
##########
@@ -0,0 +1,97 @@
+#
+# 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 unittest import mock
+
+import pytest
+from mock import patch
+from requests import HTTPError
+from tenacity import RetryError
+
+from airflow.providers.google.cloud.hooks import dataprep
+
+JOB_ID = 1234567
+URL = "https://api.clouddataprep.com/v4/jobGroups"
+TOKEN = "1111"
+EXTRA = {"token": TOKEN}
+
+
+@pytest.fixture(scope="class")
+def mock_hook():
+    with mock.patch("airflow.hooks.base_hook.BaseHook.get_connection") as conn:
+        hook = dataprep.GoogleDataprepHook(dataprep_conn_id="dataprep_conn_id")
+        conn.return_value.extra_dejson = EXTRA
+        yield hook
+
+
+class TestGoogleDataprepHook:
+    def test_get_token(self, mock_hook):
+        assert mock_hook._token == TOKEN
+
+    @patch("airflow.providers.google.cloud.hooks.dataprep.requests.get")
+    def test_mock_should_be_called_once_with_params(self, mock_get_request, mock_hook):
+        mock_hook.get_jobs_for_job_group(job_id=JOB_ID)
+        mock_get_request.assert_called_once_with(
+            f"{URL}/{JOB_ID}/jobs",
+            headers={
+                "Content-Type": "application/json",
+                "Authorization": f"Bearer {TOKEN}",
+            },
+        )
+
+    @patch(
+        "airflow.providers.google.cloud.hooks.dataprep.requests.get",
+        side_effect=[HTTPError(), mock.MagicMock()],
+    )
+    def test_should_pass_after_retry(self, mock_get_request, mock_hook):
+        mock_hook.get_jobs_for_job_group(JOB_ID)
+        assert mock_get_request.call_count == 2
+
+    @patch(
+        "airflow.providers.google.cloud.hooks.dataprep.requests.get",
+        side_effect=[mock.MagicMock(), HTTPError()],
+    )
+    def test_should_not_retry_after_success(self, mock_get_request, mock_hook):
+        mock_hook.get_jobs_for_job_group.retry.sleep = mock.Mock()  # pylint: disable=no-member
+        mock_hook.get_jobs_for_job_group(JOB_ID)
+        assert mock_get_request.call_count == 1
+
+    @patch(
+        "airflow.providers.google.cloud.hooks.dataprep.requests.get",
+        side_effect=[
+            HTTPError(),
+            HTTPError(),
+            HTTPError(),
+            HTTPError(),
+            mock.MagicMock(),
+        ],
+    )
+    def test_should_retry_after_four_errors(self, mock_get_request, mock_hook):
+        mock_hook.get_jobs_for_job_group.retry.sleep = mock.Mock()  # pylint: disable=no-member
+        mock_hook.get_jobs_for_job_group(JOB_ID)
+        assert mock_get_request.call_count == 5
+
+    @patch(
+        "airflow.providers.google.cloud.hooks.dataprep.requests.get",
+        side_effect=[HTTPError(), HTTPError(), HTTPError(), HTTPError(), HTTPError()],
+    )
+    def test_raise_error_after_five_calls(self, mock_get_request, mock_hook):

Review comment:
       Should  we mention the number of retries and exponential back-off in the docs somewhere?  I am not sure about that one. I think we are not mentioning it elsewhere (assuming that the hard-coded values are reasonable). But maybe (possibly in a separate PR) we could make it more explicit on the typical retry scenarios we use for GCP classes? Or maybe we should make it somehow configurable for all GCP classes ? WDYT @turbaszek @mik-laj ?




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

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