You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "VinceLegendre (via GitHub)" <gi...@apache.org> on 2023/02/16 15:47:25 UTC

[GitHub] [airflow] VinceLegendre commented on a diff in pull request #28525: Add CloudRunExecuteJobOperator

VinceLegendre commented on code in PR #28525:
URL: https://github.com/apache/airflow/pull/28525#discussion_r1108674510


##########
airflow/providers/google/cloud/hooks/cloud_run.py:
##########
@@ -0,0 +1,218 @@
+#
+# 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 a Google Cloud Run Hook."""
+from __future__ import annotations
+
+import json
+import time
+from typing import Sequence, Dict, Any, Callable
+
+from googleapiclient.discovery import build
+from google.api_core.client_options import ClientOptions
+
+from airflow.providers.google.common.hooks.base_google import GoogleBaseHook
+from airflow.utils.log.logging_mixin import LoggingMixin
+
+DEFAULT_CLOUD_RUN_REGION = "us-central1"
+
+
+class CloudRunJobSteps:
+    """
+    Helper class with Cloud Run job status.
+    Reference: https://cloud.google.com/run/docs/reference/rest/v1/namespaces.jobs#JobStatus
+    """
+    EXEC_STEP_COMPLETED = 'Completed'
+    EXEC_STEP_RESOURCES_AVAILABLE = 'ResourcesAvailable'
+    EXEC_STEP_STARTED = 'Started'
+    AWAITING_STEPS = {EXEC_STEP_STARTED, EXEC_STEP_RESOURCES_AVAILABLE}
+    ALL_STEPS = [EXEC_STEP_COMPLETED, EXEC_STEP_RESOURCES_AVAILABLE, EXEC_STEP_STARTED]
+
+
+class _CloudRunJobExecutionController(LoggingMixin):
+    """
+    Interface for communication with Google API.
+
+    :param cloud_run: Discovery resource
+    :param project_id: The Google Cloud Project ID.
+    :param execution_id: ID of a Cloud Run Job execution.
+    :param poll_sleep: The status refresh rate for pending operations.
+    :param num_retries: Maximum number of retries in case of connection problems.
+    :param wait_until_finished: If True, wait for the end of pipeline execution before exiting.
+        If False,it only submits job and check once is job not in terminal state.
+    """
+    def __init__(
+        self,
+        cloud_run: Any,
+        project_id: str,
+        execution_id: str | None = None,
+        poll_sleep: int = 10,
+        num_retries: int = 0,
+        wait_until_finished: bool | None = None
+    ) -> None:
+
+        super().__init__()
+        self._cloud_run = cloud_run
+        self._project_id = project_id
+        self._exec_id = execution_id
+        self._poll_sleep = poll_sleep
+        self._num_retries = num_retries
+        self._execution: Dict | None = None
+        self._execution_state: str | None = None
+        self.wait_until_finished = wait_until_finished
+
+    def _fetch_execution_by_id(self):
+        """
+        Helper method to fetch the execution with the specified execution ID.
+
+        :return: the Cloud Run job execution
+        """
+        self.log.debug(f'Fetching information for job execution {self._exec_id}.')
+        return (
+            self._cloud_run
+            .namespaces()
+            .executions()
+            .get(name=f'namespaces/{self._project_id}/executions/{self._exec_id}')
+            .execute(num_retries=self._num_retries)
+        )
+
+    def _check_execution_state(self) -> bool:
+        """
+        Helper method to check the state of job execution
+        if execution failed raise exception
+
+        :return: True if execution is done.
+        :raise: Exception
+        """
+        if 'conditions' not in self._execution['status']:
+            raise Exception(f'An error occurred when starting Google Cloud Run job execution {self._exec_id}.'
+                            f'\n See details at {self._execution["status"]["logUri"]}.')
+        conditions = self._execution['status']['conditions']
+        steps = []
+        for c in conditions:
+            step = c['type']
+            verdict = c['status']
+            if step not in CloudRunJobSteps.ALL_STEPS:
+                raise Exception(f'Unknown state {step} found for Google Cloud Run job execution {self._exec_id}. '
+                                f'See details at {self._execution["status"]["logUri"]}.')
+            if verdict == 'False':
+                # This verdict means that a step failed,
+                # therefore the execution has failed
+                raise Exception(f'Cloud Run Job execution {self._exec_id} has failed. '
+                                f'See details at {self._execution["status"]["logUri"]}.')
+            if verdict == 'Unknown':
+                # This verdict means that the step is not completed yet,
+                # therefore the execution cannot be finished yet
+                return False
+            if verdict == 'True':
+                steps.append(step)
+        return CloudRunJobSteps.EXEC_STEP_COMPLETED in steps
+
+    def wait_for_done(self) -> None:
+        """Helper method to wait for result of job execution."""
+        self.log.info(f'Starting to poll status for Google Cloud Run job execution {self._exec_id}.')
+        self._execution = self._fetch_execution_by_id()
+        self.log.info(json.dumps(self._execution))
+        while not self._check_execution_state():
+            self.log.info(f'Waiting for execution completion. Sleeping {str(self._poll_sleep)} seconds.')
+            time.sleep(self._poll_sleep)
+            self._execution = self._fetch_execution_by_id()
+
+
+class CloudRunJobHook(GoogleBaseHook):
+    """
+    Hook for Google Cloud Run.
+
+    All the methods in the hook where project_id is used must be called with
+    keyword arguments rather than positional.
+    """
+
+    def __init__(
+        self,
+        gcp_conn_id: str = "google_cloud_default",
+        region: str = DEFAULT_CLOUD_RUN_REGION,
+        delegate_to: str | None = None,
+        poll_sleep: int = 10,
+        impersonation_chain: str | Sequence[str] | None = None,
+        delete_timeout: int | None = 5 * 60,
+        wait_until_finished: bool | None = None,
+        job_exec_cold_start: int | None = 10
+    ) -> None:
+        self.region = region
+        self.poll_sleep = poll_sleep
+        self.delete_timeout = delete_timeout
+        self.wait_until_finished = wait_until_finished
+        self.job_id: str | None = None
+        super().__init__(
+            gcp_conn_id=gcp_conn_id,
+            delegate_to=delegate_to,
+            impersonation_chain=impersonation_chain
+        )
+        self.job_exec_cold_start = job_exec_cold_start
+
+    def get_conn(self) -> build:
+        """Returns a Google Cloud Run service object."""
+        http_authorized = self._authorize()
+
+        # Use a regional endpoint since job execution is not possible from the global endpoint
+        client_options = ClientOptions(api_endpoint=f'https://{self.region}-run.googleapis.com')
+        return build('run', 'v1', client_options=client_options,
+                     http=http_authorized, cache_discovery=False)

Review Comment:
   Hi @lwyszomi @steren 
   
   Cannot install the python client library (google-cloud-run>=0.7.0) as it breaks other dependencies requirements.
   Happy to use the JobsClient if we manage to install google-cloud-run library



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