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 2021/01/08 09:34:14 UTC

[GitHub] [airflow] mik-laj commented on a change in pull request #13366: Add Google Cloud Workflows Operators

mik-laj commented on a change in pull request #13366:
URL: https://github.com/apache/airflow/pull/13366#discussion_r553836124



##########
File path: airflow/providers/google/cloud/operators/workflows.py
##########
@@ -0,0 +1,638 @@
+# 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.
+import hashlib
+import json
+import re
+import uuid
+from typing import Dict, Optional, Sequence, Tuple, Union
+
+from google.api_core.retry import Retry
+
+# pylint: disable=no-name-in-module
+from google.cloud.workflows.executions_v1beta import Execution
+from google.cloud.workflows_v1beta import Workflow
+
+# pylint: enable=no-name-in-module
+from google.protobuf.field_mask_pb2 import FieldMask
+
+from airflow.models import BaseOperator
+from airflow.providers.google.cloud.hooks.workflows import WorkflowsHook
+
+
+class WorkflowsCreateWorkflowOperator(BaseOperator):
+    """
+    Creates a new workflow. If a workflow with the specified name
+    already exists in the specified project and location, the long
+    running operation will return
+    [ALREADY_EXISTS][google.rpc.Code.ALREADY_EXISTS] error.
+
+    :param workflow: Required. Workflow to be created.
+    :type workflow: Dict
+    :param workflow_id: Required. The ID of the workflow to be created.
+    :type workflow_id: str
+    :param project_id: Required. The ID of the Google Cloud project the cluster belongs to.
+    :type project_id: str
+    :param location: Required. The Cloud Dataproc region in which to handle the request.
+    :type location: str
+    :param retry: A retry object used to retry requests. If ``None`` is specified, requests will not be
+        retried.
+    :type retry: google.api_core.retry.Retry
+    :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if
+        ``retry`` is specified, the timeout applies to each individual attempt.
+    :type timeout: float
+    :param metadata: Additional metadata that is provided to the method.
+    :type metadata: Sequence[Tuple[str, str]]
+    """
+
+    template_fields = ("location", "workflow", "workflow_id")
+    template_fields_renderers = {"workflow": "json"}
+
+    def __init__(
+        self,
+        *,
+        workflow: Dict,
+        workflow_id: str,
+        location: str,
+        project_id: str,
+        retry: Optional[Retry] = None,
+        timeout: Optional[float] = None,
+        metadata: Optional[Sequence[Tuple[str, str]]] = None,
+        gcp_conn_id: str = "google_cloud_default",
+        force_rerun: bool = False,
+        impersonation_chain: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ):
+        super().__init__(**kwargs)
+
+        self.workflow = workflow
+        self.workflow_id = workflow_id
+        self.location = location
+        self.project_id = project_id
+        self.retry = retry
+        self.timeout = timeout
+        self.metadata = metadata
+        self.gcp_conn_id = gcp_conn_id
+        self.impersonation_chain = impersonation_chain
+        self.force_rerun = force_rerun
+
+    def _workflow_id(self, context):
+        if self.workflow_id and not self.force_rerun:
+            # If users provide workflow id then assuring the idempotency
+            # is on their side
+            return self.workflow_id
+
+        if self.force_rerun:
+            hash_base = str(uuid.uuid4())
+        else:
+            hash_base = json.dumps(self.workflow, sort_keys=True)
+
+        # We are limited by allowed length of workflow_id so
+        # we use hash of whole information
+        exec_date = context['execution_date'].isoformat()
+        base = f"airflow_{self.dag_id}_{self.task_id}_{exec_date}_{hash_base}"
+        workflow_id = hashlib.md5(base.encode()).hexdigest()
+        return re.sub(r"[:\-+.]", "_", workflow_id)
+
+    def execute(self, context):
+        hook = WorkflowsHook(gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain)
+        self.log.info("Creating workflow")
+        operation = hook.create_workflow(
+            workflow=self.workflow,
+            workflow_id=self._workflow_id(context),
+            location=self.location,
+            project_id=self.project_id,
+            retry=self.retry,
+            timeout=self.timeout,
+            metadata=self.metadata,
+        )
+        operation.result()
+        return Workflow.to_dict(operation)

Review comment:
       I am not sure if this is the correct code. It looks a little different in other places.
   https://github.com/apache/airflow/blob/6570df871354f6bdefce88f21099fb09add096a4/airflow/providers/google/cloud/operators/dataproc.py#L546-L548




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