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_r261007224
########## 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): + """ + Creates a transfer job that runs periodically. + + .. warning:: + + This operator is NOT idempotent. If you run it many times, many transfer + jobs will be created in the Google Cloud Platform. + + .. seealso:: + For more information on how to use this operator, take a look at the guide: + :ref:`howto/operator:GcpTransferServiceJobCreateOperator` + + :param body: (Required) The request body, as described in + https://cloud.google.com/storage-transfer/docs/reference/rest/v1/transferJobs/create#request-body + With three additional improvements: + + * dates can be given in the form :class:`datetime.date` + * times can be given in the form :class:`datetime.time` + * credentials to Amazon Web Service should be stored in the connection and indicated by the + aws_conn_id parameter + + :type body: dict + :param aws_conn_id: The connection ID used to retrieve credentials to + Amazon Web Service. + :type aws_conn_id: str + :param gcp_conn_id: The connection ID used to connect to Google Cloud + Platform. + :type gcp_conn_id: str + :param api_version: API version used (e.g. v1). + :type api_version: str + """ + + # [START gcp_transfer_job_create_template_fields] + template_fields = ('body', 'gcp_conn_id', 'aws_conn_id') + # [END gcp_transfer_job_create_template_fields] + + @apply_defaults + def __init__( + self, + body, + aws_conn_id='aws_default', + gcp_conn_id='google_cloud_default', + api_version='v1', + *args, + **kwargs + ): + super(GcpTransferServiceJobCreateOperator, self).__init__(*args, **kwargs) + self.body = deepcopy(body) + self.aws_conn_id = aws_conn_id + self.gcp_conn_id = gcp_conn_id + self.api_version = api_version + self._validate_inputs() + + def _validate_inputs(self): + TransferJobValidator(body=self.body).validate_body() + + def execute(self, context): + TransferJobPreprocessor(body=self.body, aws_conn_id=self.aws_conn_id).process_body() + hook = GCPTransferServiceHook(api_version=self.api_version, gcp_conn_id=self.gcp_conn_id) + return hook.create_transfer_job(body=self.body) + + +class GcpTransferServiceJobUpdateOperator(BaseOperator): + """ + Updates a transfer job that runs periodically. + + .. seealso:: + For more information on how to use this operator, take a look at the guide: + :ref:`howto/operator:GcpTransferServiceJobUpdateOperator` + + :param job_name: (Required) Name of the job to be updated + :type job_name: str + :param body: (Required) The request body, as described in + https://cloud.google.com/storage-transfer/docs/reference/rest/v1/transferJobs/patch#request-body + With three additional improvements: + + * dates can be given in the form :class:`datetime.date` + * times can be given in the form :class:`datetime.time` + * credentials to Amazon Web Service should be stored in the connection and indicated by the + aws_conn_id parameter + + :type body: dict + :param aws_conn_id: The connection ID used to retrieve credentials to + Amazon Web Service. + :type aws_conn_id: str + :param gcp_conn_id: The connection ID used to connect to Google Cloud + Platform. + :type gcp_conn_id: str + :param api_version: API version used (e.g. v1). + :type api_version: str + """ + + # [START gcp_transfer_job_update_template_fields] + template_fields = ('job_name', 'body', 'gcp_conn_id', 'aws_conn_id') + # [END gcp_transfer_job_update_template_fields] + + @apply_defaults + def __init__( + self, + job_name, + body, + aws_conn_id='aws_default', + gcp_conn_id='google_cloud_default', + api_version='v1', + *args, + **kwargs + ): + super(GcpTransferServiceJobUpdateOperator, self).__init__(*args, **kwargs) + self.job_name = job_name + self.body = body + self.gcp_conn_id = gcp_conn_id + self.api_version = api_version + self.aws_conn_id = aws_conn_id + self._validate_inputs() + + def _validate_inputs(self): + TransferJobValidator(body=self.body).validate_body() + if not self.job_name: + raise AirflowException("The required parameter 'job_name' is empty or None") + + def execute(self, context): + TransferJobPreprocessor(body=self.body, aws_conn_id=self.aws_conn_id).process_body() + hook = GCPTransferServiceHook(api_version=self.api_version, gcp_conn_id=self.gcp_conn_id) + return hook.update_transfer_job(job_name=self.job_name, body=self.body) + + +class GcpTransferServiceJobDeleteOperator(BaseOperator): + """ + Delete a transfer job. + + .. seealso:: + For more information on how to use this operator, take a look at the guide: + :ref:`howto/operator:GcpTransferServiceJobDeleteOperator` + + :param job_name: (Required) Name of the TRANSFER operation + :type job_name: str + :param project_id: (Optional) the ID of the project that owns the Transfer + Job. If set to None or missing, the default project_id from the GCP + connection is used. + :type project_id: str + :param gcp_conn_id: The connection ID used to connect to Google Cloud + Platform. + :type gcp_conn_id: str + :param api_version: API version used (e.g. v1). + :type api_version: str + """ + + # [START gcp_transfer_job_delete_template_fields] + template_fields = ('job_name', 'project_id', 'gcp_conn_id') + # [END gcp_transfer_job_delete_template_fields] + + @apply_defaults + def __init__( + self, job_name, gcp_conn_id='google_cloud_default', api_version='v1', project_id=None, *args, **kwargs + ): + super(GcpTransferServiceJobDeleteOperator, self).__init__(*args, **kwargs) + self.job_name = job_name + self.project_id = project_id + self.gcp_conn_id = gcp_conn_id + self.api_version = api_version + self._validate_inputs() + + def _validate_inputs(self): + if not self.job_name: + raise AirflowException("The required parameter 'job_name' is empty or None") + + def execute(self, context): + self._validate_inputs() + hook = GCPTransferServiceHook(api_version=self.api_version, gcp_conn_id=self.gcp_conn_id) + hook.delete_transfer_job(job_name=self.job_name, project_id=self.project_id) + + +class GcpTransferServiceOperationGetOperator(BaseOperator): + """ + Gets the latest state of a long-running operation in Google Storage Transfer + Service. + + .. seealso:: + For more information on how to use this operator, take a look at the guide: + :ref:`howto/operator:GcpTransferServiceOperationGetOperator` + + :param operation_name: (Required) Name of the transfer operation. + :type operation_name: str + :param gcp_conn_id: The connection ID used to connect to Google + Cloud Platform. + :type gcp_conn_id: str + :param api_version: API version used (e.g. v1). + :type api_version: str + """ + + # [START gcp_transfer_operation_get_template_fields] + template_fields = ('operation_name', 'gcp_conn_id') + # [END gcp_transfer_operation_get_template_fields] + + @apply_defaults + def __init__(self, operation_name, gcp_conn_id='google_cloud_default', api_version='v1', *args, **kwargs): + super(GcpTransferServiceOperationGetOperator, self).__init__(*args, **kwargs) + self.operation_name = operation_name + self.gcp_conn_id = gcp_conn_id + self.api_version = api_version + self._validate_inputs() + + def _validate_inputs(self): + if not self.operation_name: + raise AirflowException("The required parameter 'operation_name' is empty or None") + + def execute(self, context): + hook = GCPTransferServiceHook(api_version=self.api_version, gcp_conn_id=self.gcp_conn_id) + operation = hook.get_transfer_operation(operation_name=self.operation_name) + self.log.info(operation) + return operation + + +class GcpTransferServiceOperationsListOperator(BaseOperator): + """ + Lists long-running operations in Google Storage Transfer + Service that match the specified filter. + + .. seealso:: + For more information on how to use this operator, take a look at the guide: + :ref:`howto/operator:GcpTransferServiceOperationsListOperator` + + :param filter: (Required) A request filter, as described in + https://cloud.google.com/storage-transfer/docs/reference/rest/v1/transferJobs/list#body.QUERY_PARAMETERS.filter + :type filter: dict + :param gcp_conn_id: The connection ID used to connect to Google + Cloud Platform. + :type gcp_conn_id: str + :param api_version: API version used (e.g. v1). + :type api_version: str + """ + + # [START gcp_transfer_operations_list_template_fields] + template_fields = ('filter', 'gcp_conn_id') + # [END gcp_transfer_operations_list_template_fields] + + def __init__(self, filter, gcp_conn_id='google_cloud_default', api_version='v1', *args, **kwargs): + super(GcpTransferServiceOperationsListOperator, self).__init__(*args, **kwargs) + self.filter = filter + self.gcp_conn_id = gcp_conn_id + self.api_version = api_version + self._validate_inputs() + + def _validate_inputs(self): + if not self.filter: + raise AirflowException("The required parameter 'filter' is empty or None") + + def execute(self, context): + hook = GCPTransferServiceHook(api_version=self.api_version, gcp_conn_id=self.gcp_conn_id) + operations_list = hook.list_transfer_operations(filter=self.filter) + self.log.info(operations_list) + return operations_list + + +class GcpTransferServiceOperationPauseOperator(BaseOperator): + """ + Pauses a transfer operation in Google Storage Transfer Service. + + .. seealso:: + For more information on how to use this operator, take a look at the guide: + :ref:`howto/operator:GcpTransferServiceOperationPauseOperator` + + :param operation_name: (Required) Name of the transfer operation. + :type operation_name: str + :param gcp_conn_id: The connection ID used to connect to Google Cloud Platform. + :type gcp_conn_id: str + :param api_version: API version used (e.g. v1). + :type api_version: str + """ + + # [START gcp_transfer_operation_pause_template_fields] + template_fields = ('operation_name', 'gcp_conn_id') + # [END gcp_transfer_operation_pause_template_fields] + + @apply_defaults + def __init__(self, operation_name, gcp_conn_id='google_cloud_default', api_version='v1', *args, **kwargs): + super(GcpTransferServiceOperationPauseOperator, self).__init__(*args, **kwargs) + self.operation_name = operation_name + self.gcp_conn_id = gcp_conn_id + self.api_version = api_version + self._validate_inputs() + + def _validate_inputs(self): + if not self.operation_name: + raise AirflowException("The required parameter 'operation_name' is empty or None") + + def execute(self, context): + hook = GCPTransferServiceHook(api_version=self.api_version, gcp_conn_id=self.gcp_conn_id) + hook.pause_transfer_operation(operation_name=self.operation_name) + + +class GcpTransferServiceOperationResumeOperator(BaseOperator): + """ + Resumes a transfer operation in Google Storage Transfer Service. + + .. seealso:: + For more information on how to use this operator, take a look at the guide: + :ref:`howto/operator:GcpTransferServiceOperationResumeOperator` + + :param operation_name: (Required) Name of the transfer operation. + :type operation_name: str + :param gcp_conn_id: The connection ID used to connect to Google Cloud Platform. + :param api_version: API version used (e.g. v1). + :type api_version: str + :type gcp_conn_id: str + """ + + # [START gcp_transfer_operation_resume_template_fields] + template_fields = ('operation_name', 'gcp_conn_id', 'api_version') + # [END gcp_transfer_operation_resume_template_fields] + + @apply_defaults + def __init__(self, operation_name, gcp_conn_id='google_cloud_default', api_version='v1', *args, **kwargs): + Review comment: nit: extra line ---------------------------------------------------------------- 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
