sdevani commented on a change in pull request #4792:  [AIRFLOW-3659] Create 
Google Cloud Transfer Service Operators 
URL: https://github.com/apache/airflow/pull/4792#discussion_r261270005
 
 

 ##########
 File path: airflow/contrib/operators/gcp_transfer_operator.py
 ##########
 @@ -0,0 +1,753 @@
+# -*- coding: utf-8 -*-
+#
+# 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 copy import deepcopy
+from datetime import date, time
+
+from airflow import AirflowException
+from airflow.contrib.hooks.gcp_transfer_hook import GCPTransferServiceHook, 
GcpTransferJobsStatus
+from airflow.models import BaseOperator
+from airflow.utils.decorators import apply_defaults
+
+try:
+    from airflow.contrib.hooks.aws_hook import AwsHook
+except ImportError:  # pragma: no cover
+    AwsHook = None
+
+
+class TransferJobPreprocessor:
+    def __init__(self, body, aws_conn_id='aws_default'):
+        self.body = body
+        self.aws_conn_id = aws_conn_id
+
+    def _inject_aws_credentials(self):
+        if 'transferSpec' not in self.body or 'awsS3DataSource' not in 
self.body['transferSpec']:
+            return
+
+        aws_hook = AwsHook(self.aws_conn_id)
+        aws_credentials = aws_hook.get_credentials()
+        aws_access_key_id = aws_credentials.access_key
+        aws_secret_access_key = aws_credentials.secret_key
+        self.body['transferSpec']['awsS3DataSource']["awsAccessKey"] = {
+            "accessKeyId": aws_access_key_id,
+            "secretAccessKey": aws_secret_access_key,
+        }
+
+    def _reformat_date(self, field_key):
+        schedule = self.body['schedule']
+        if field_key not in schedule:
+            return
+        if isinstance(schedule[field_key], date):
+            schedule[field_key] = 
self._convert_date_to_dict(schedule[field_key])
+
+    def _reformat_time(self, field_key):
+        schedule = self.body['schedule']
+        if field_key not in schedule:
+            return
+        if isinstance(schedule[field_key], time):
+            schedule[field_key] = 
self._convert_time_to_dict(schedule[field_key])
+
+    def _reformat_schedule(self):
+        if 'schedule' not in self.body:
+            return
+        self._reformat_date('scheduleStartDate')
+        self._reformat_date('scheduleEndDate')
+        self._reformat_time('startTimeOfDay')
+
+    def process_body(self):
+        self._inject_aws_credentials()
+        self._reformat_schedule()
+        return self.body
+
+    @staticmethod
+    def _convert_date_to_dict(field_date):
+        """
+        Convert native python ``datetime.date`` object  to a format supported 
by the API
+        """
+        return {'day': field_date.day, 'month': field_date.month, 'year': 
field_date.year}
+
+    @staticmethod
+    def _convert_time_to_dict(time):
+        """
+        Convert native python ``datetime.time`` object  to a format supported 
by the API
+        """
+        return {"hours": time.hour, "minutes": time.minute, "seconds": 
time.second}
+
+
+class TransferJobValidator:
+    def __init__(self, body):
+        self.body = body
+
+    def _verify_data_source(self):
+        is_gcs = 'gcsDataSource' in self.body['transferSpec']
+        is_aws_s3 = 'awsS3DataSource' in self.body['transferSpec']
+        is_http = 'httpDataSource' in self.body['transferSpec']
+
+        sources_count = sum([is_gcs, is_aws_s3, is_http])
+        if sources_count != 0 and sources_count != 1:
+            raise AirflowException(
+                "More than one data source detected. Please choose exactly one 
data source from: "
+                "gcsDataSource, awsS3DataSource and httpDataSource."
+            )
+
+    def _restrict_aws_credentials(self):
+        if 'awsS3DataSource' not in self.body['transferSpec']:
+            return
+
+        if 'awsAccessKey' in self.body['transferSpec']['awsS3DataSource']:
+            raise AirflowException(
+                "AWS credentials detected inside the body parameter 
(awsAccessKey). This is not allowed, "
+                "please use Airflow connections to store credentials."
+            )
+
+    def _restrict_empty_body(self):
+        if not self.body:
+            raise AirflowException("The required parameter 'body' is empty or 
None")
+
+    def validate_body(self):
+        self._restrict_empty_body()
+
+        if 'transferSpec' not in self.body:
+            return
+
+        self._restrict_aws_credentials()
+        self._verify_data_source()
+
+
+class GcpTransferServiceJobCreateOperator(BaseOperator):
 
 Review comment:
   I could image operator discoverability can be challenging with many 
operators in 1 file. I think the idea of having sub directories has been shot 
down in the past - that would be ideal and would allow us to split this file 
into multiple smaller ones.
   
   Maybe an alternative would be a file level comment describing the operators 
in here?

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
[email protected]


With regards,
Apache Git Services

Reply via email to