|
| 1 | +# |
| 2 | +# Licensed to the Apache Software Foundation (ASF) under one |
| 3 | +# or more contributor license agreements. See the NOTICE file |
| 4 | +# distributed with this work for additional information |
| 5 | +# regarding copyright ownership. The ASF licenses this file |
| 6 | +# to you under the Apache License, Version 2.0 (the |
| 7 | +# "License"); you may not use this file except in compliance |
| 8 | +# with the License. You may obtain a copy of the License at |
| 9 | +# |
| 10 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +# |
| 12 | +# Unless required by applicable law or agreed to in writing, |
| 13 | +# software distributed under the License is distributed on an |
| 14 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | +# KIND, either express or implied. See the License for the |
| 16 | +# specific language governing permissions and limitations |
| 17 | +# under the License. |
| 18 | +""" |
| 19 | +This module contains SFTP to Google Cloud Storage operator. |
| 20 | +""" |
| 21 | +import os |
| 22 | +from tempfile import NamedTemporaryFile |
| 23 | +from typing import Optional, Union |
| 24 | + |
| 25 | +from airflow import AirflowException |
| 26 | +from airflow.contrib.hooks.sftp_hook import SFTPHook |
| 27 | +from airflow.gcp.hooks.gcs import GoogleCloudStorageHook |
| 28 | +from airflow.models import BaseOperator |
| 29 | +from airflow.utils.decorators import apply_defaults |
| 30 | + |
| 31 | +WILDCARD = "*" |
| 32 | + |
| 33 | + |
| 34 | +class SFTPToGoogleCloudStorageOperator(BaseOperator): |
| 35 | + """ |
| 36 | + Transfer files to Google Cloud Storage from SFTP server. |
| 37 | +
|
| 38 | + .. seealso:: |
| 39 | + For more information on how to use this operator, take a look at the guide: |
| 40 | + :ref:`howto/operator:SFTPToGoogleCloudStorageOperator` |
| 41 | +
|
| 42 | + :param source_path: The sftp remote path. This is the specified file path |
| 43 | + for downloading the single file or multiple files from the SFTP server. |
| 44 | + You can use only one wildcard within your path. The wildcard can appear |
| 45 | + inside the path or at the end of the path. |
| 46 | + :type source_path: str |
| 47 | + :param destination_bucket: The bucket to upload to. |
| 48 | + :type destination_bucket: str |
| 49 | + :param destination_path: The destination name of the object in the |
| 50 | + destination Google Cloud Storage bucket. |
| 51 | + If destination_path is not provided file/files will be placed in the |
| 52 | + main bucket path. |
| 53 | + If a wildcard is supplied in the destination_path argument, this is the |
| 54 | + prefix that will be prepended to the final destination objects' paths. |
| 55 | + :type destination_path: str |
| 56 | + :param gcp_conn_id: (Optional) The connection ID used to connect to Google Cloud Platform. |
| 57 | + :type gcp_conn_id: str |
| 58 | + :param sftp_conn_id: The sftp connection id. The name or identifier for |
| 59 | + establishing a connection to the SFTP server. |
| 60 | + :type sftp_conn_id: str |
| 61 | + :param delegate_to: The account to impersonate, if any |
| 62 | + :type delegate_to: str |
| 63 | + :param mime_type: The mime-type string |
| 64 | + :type mime_type: str |
| 65 | + :param gzip: Allows for file to be compressed and uploaded as gzip |
| 66 | + :type gzip: bool |
| 67 | + :param move_object: When move object is True, the object is moved instead |
| 68 | + of copied to the new location. This is the equivalent of a mv command |
| 69 | + as opposed to a cp command. |
| 70 | + :type move_object: bool |
| 71 | + """ |
| 72 | + |
| 73 | + template_fields = ("source_path", "destination_path", "destination_bucket") |
| 74 | + |
| 75 | + @apply_defaults |
| 76 | + def __init__( |
| 77 | + self, |
| 78 | + source_path: str, |
| 79 | + destination_bucket: str, |
| 80 | + destination_path: Optional[str] = None, |
| 81 | + gcp_conn_id: str = "google_cloud_default", |
| 82 | + sftp_conn_id: str = "ssh_default", |
| 83 | + delegate_to: Optional[str] = None, |
| 84 | + mime_type: str = "application/octet-stream", |
| 85 | + gzip: bool = False, |
| 86 | + move_object: bool = False, |
| 87 | + *args, |
| 88 | + **kwargs |
| 89 | + ) -> None: |
| 90 | + super().__init__(*args, **kwargs) |
| 91 | + |
| 92 | + self.source_path = source_path |
| 93 | + self.destination_path = self._set_destination_path(destination_path) |
| 94 | + self.destination_bucket = self._set_bucket_name(destination_bucket) |
| 95 | + self.gcp_conn_id = gcp_conn_id |
| 96 | + self.mime_type = mime_type |
| 97 | + self.delegate_to = delegate_to |
| 98 | + self.gzip = gzip |
| 99 | + self.sftp_conn_id = sftp_conn_id |
| 100 | + self.move_object = move_object |
| 101 | + |
| 102 | + def execute(self, context): |
| 103 | + gcs_hook = GoogleCloudStorageHook( |
| 104 | + gcp_conn_id=self.gcp_conn_id, delegate_to=self.delegate_to |
| 105 | + ) |
| 106 | + |
| 107 | + sftp_hook = SFTPHook(self.sftp_conn_id) |
| 108 | + |
| 109 | + if WILDCARD in self.source_path: |
| 110 | + total_wildcards = self.source_path.count(WILDCARD) |
| 111 | + if total_wildcards > 1: |
| 112 | + raise AirflowException( |
| 113 | + "Only one wildcard '*' is allowed in source_path parameter. " |
| 114 | + "Found {} in {}.".format(total_wildcards, self.source_path) |
| 115 | + ) |
| 116 | + |
| 117 | + prefix, delimiter = self.source_path.split(WILDCARD, 1) |
| 118 | + base_path = os.path.dirname(prefix) |
| 119 | + |
| 120 | + files, _, _ = sftp_hook.get_tree_map( |
| 121 | + base_path, prefix=prefix, delimiter=delimiter |
| 122 | + ) |
| 123 | + |
| 124 | + for file in files: |
| 125 | + destination_path = file.replace(base_path, self.destination_path, 1) |
| 126 | + self._copy_single_object(gcs_hook, sftp_hook, file, destination_path) |
| 127 | + |
| 128 | + else: |
| 129 | + destination_object = ( |
| 130 | + self.destination_path |
| 131 | + if self.destination_path |
| 132 | + else self.source_path.rsplit("/", 1)[1] |
| 133 | + ) |
| 134 | + self._copy_single_object( |
| 135 | + gcs_hook, sftp_hook, self.source_path, destination_object |
| 136 | + ) |
| 137 | + |
| 138 | + def _copy_single_object( |
| 139 | + self, |
| 140 | + gcs_hook: GoogleCloudStorageHook, |
| 141 | + sftp_hook: SFTPHook, |
| 142 | + source_path: str, |
| 143 | + destination_object: str, |
| 144 | + ) -> None: |
| 145 | + """ |
| 146 | + Helper function to copy single object. |
| 147 | + """ |
| 148 | + self.log.info( |
| 149 | + "Executing copy of %s to gs://%s/%s", |
| 150 | + source_path, |
| 151 | + self.destination_bucket, |
| 152 | + destination_object, |
| 153 | + ) |
| 154 | + |
| 155 | + with NamedTemporaryFile("w") as tmp: |
| 156 | + sftp_hook.retrieve_file(source_path, tmp.name) |
| 157 | + |
| 158 | + gcs_hook.upload( |
| 159 | + bucket_name=self.destination_bucket, |
| 160 | + object_name=destination_object, |
| 161 | + filename=tmp.name, |
| 162 | + mime_type=self.mime_type, |
| 163 | + ) |
| 164 | + |
| 165 | + if self.move_object: |
| 166 | + self.log.info("Executing delete of %s", source_path) |
| 167 | + sftp_hook.delete_file(source_path) |
| 168 | + |
| 169 | + @staticmethod |
| 170 | + def _set_destination_path(path: Union[str, None]) -> str: |
| 171 | + if path is not None: |
| 172 | + return path.lstrip("/") if path.startswith("/") else path |
| 173 | + return "" |
| 174 | + |
| 175 | + @staticmethod |
| 176 | + def _set_bucket_name(name: str) -> str: |
| 177 | + bucket = name if not name.startswith("gs://") else name[5:] |
| 178 | + return bucket.strip("/") |
0 commit comments