FHoffmannCode commented on a change in pull request #10991:
URL: https://github.com/apache/airflow/pull/10991#discussion_r494812162
##########
File path: airflow/providers/microsoft/azure/hooks/azure_fileshare.py
##########
@@ -96,6 +96,26 @@ def list_directories_and_files(self, share_name,
directory_name=None, **kwargs):
"""
return self.get_conn().list_directories_and_files(share_name,
directory_name, **kwargs)
+ def list_files(self, share_name, directory_name=None, **kwargs):
Review comment:
sure thing, done
##########
File path: airflow/providers/google/cloud/transfers/azure_fileshare_to_gcs.py
##########
@@ -0,0 +1,217 @@
+#
+# 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 warnings
+from tempfile import NamedTemporaryFile
+from typing import Optional, Union, Sequence, Iterable
+
+from airflow import AirflowException
+from airflow.models import BaseOperator
+from airflow.providers.google.cloud.hooks.gcs import _parse_gcs_url, GCSHook
+from airflow.providers.microsoft.azure.hooks.azure_fileshare import
AzureFileShareHook
+from airflow.utils.decorators import apply_defaults
+
+
+class AzureFileShareToGCSOperator(BaseOperator):
+ """
+ Synchronizes a Azure FileShare directory content (excluding
subdirectories),
+ possibly filtered by a prefix, with a Google Cloud Storage destination
path.
+
+ :param share_name: The Azure FileShare share where to find the objects.
(templated)
+ :type share_name: str
+ :directory_name: (Optional) Path to Azure FileShare directory which
content is to be transfered.
+ Defaults to root directory (templated)
+ :param prefix: Prefix string which filters objects whose name begin with
+ such prefix. (templated)
+ :type prefix: str
+ :param wasb_conn_id: The source WASB connection
+ :type wasb_conn_id: str
+ :param gcp_conn_id: (Optional) The connection ID used to connect to Google
Cloud.
+ :type gcp_conn_id: str
+ :param dest_gcs_conn_id: (Deprecated) The connection ID used to connect to
Google Cloud.
+ This parameter has been deprecated. You should pass the gcp_conn_id
parameter instead.
+ :type dest_gcs_conn_id: str
+ :param dest_gcs: The destination Google Cloud Storage bucket and prefix
+ where you want to store the files. (templated)
+ :type dest_gcs: str
+ :param delegate_to: Google account to impersonate using domain-wide
delegation of authority,
+ if any. For this to work, the service account making the request must
have
+ domain-wide delegation enabled.
+ :type delegate_to: str
+ :param replace: Whether you want to replace existing destination files
+ or not.
+ :type replace: bool
+ :param gzip: Option to compress file for upload
+ :type gzip: bool
+ :param google_impersonation_chain: Optional Google service account to
impersonate using
+ short-term credentials, or chained list of accounts required to get
the access_token
+ of the last account in the list, which will be impersonated in the
request.
+ If set as a string, the account must grant the originating account
+ the Service Account Token Creator IAM role.
+ If set as a sequence, the identities from the list must grant
+ Service Account Token Creator IAM role to the directly preceding
identity, with first
+ account from the list granting this role to the originating account
(templated).
+ :type google_impersonation_chain: Union[str, Sequence[str]]
+
+
+ **Example**:
+
+ .. code-block:: python
+
+ azure_fileshare_to_gcs_op = AzureFileShareToGCSOperator(
+ task_id='azure_fileshare_to_gcs_example',
+ share='my-azure-share',
+ directory_name='mydir/anotherdir',
+ prefix='data/customers-201804',
+ dest_gcs_conn_id='google_cloud_default',
+ dest_gcs='gs://my.gcs.bucket/some/customers/',
+ replace=False,
+ gzip=True,
+ dag=my-dag
+ )
+
+ Note that ``share``, ``directory_name``, ``prefix``, ``delimiter`` and
``dest_gcs`` are
+ templated, so you can use variables in them if you wish.
+ """
+
+ template_fields: Iterable[str] = (
+ 'share',
+ 'directory_name',
+ 'prefix',
+ 'dest_gcs',
+ 'google_impersonation_chain',
+ )
+
+ @apply_defaults
+ def __init__(
+ self,
+ *,
+ share_name,
+ directory_name=None,
+ prefix='',
+ wasb_conn_id='wasb_default',
+ gcp_conn_id='google_cloud_default',
+ dest_gcs_conn_id=None,
+ dest_gcs=None,
+ delegate_to=None,
+ replace=False,
+ gzip=False,
+ google_impersonation_chain: Optional[Union[str, Sequence[str]]] = None,
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+
+ self.share_name = share_name
+ self.directory_name = directory_name
+ self.prefix = prefix
+ self.wasb_conn_id = wasb_conn_id
+
+ if dest_gcs_conn_id:
Review comment:
ok, removed
##########
File path: airflow/providers/google/cloud/transfers/azure_fileshare_to_gcs.py
##########
@@ -0,0 +1,217 @@
+#
+# 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 warnings
+from tempfile import NamedTemporaryFile
+from typing import Optional, Union, Sequence, Iterable
+
+from airflow import AirflowException
+from airflow.models import BaseOperator
+from airflow.providers.google.cloud.hooks.gcs import _parse_gcs_url, GCSHook
+from airflow.providers.microsoft.azure.hooks.azure_fileshare import
AzureFileShareHook
+from airflow.utils.decorators import apply_defaults
+
+
+class AzureFileShareToGCSOperator(BaseOperator):
+ """
+ Synchronizes a Azure FileShare directory content (excluding
subdirectories),
+ possibly filtered by a prefix, with a Google Cloud Storage destination
path.
+
+ :param share_name: The Azure FileShare share where to find the objects.
(templated)
+ :type share_name: str
+ :directory_name: (Optional) Path to Azure FileShare directory which
content is to be transfered.
+ Defaults to root directory (templated)
+ :param prefix: Prefix string which filters objects whose name begin with
+ such prefix. (templated)
+ :type prefix: str
+ :param wasb_conn_id: The source WASB connection
+ :type wasb_conn_id: str
+ :param gcp_conn_id: (Optional) The connection ID used to connect to Google
Cloud.
+ :type gcp_conn_id: str
+ :param dest_gcs_conn_id: (Deprecated) The connection ID used to connect to
Google Cloud.
+ This parameter has been deprecated. You should pass the gcp_conn_id
parameter instead.
+ :type dest_gcs_conn_id: str
+ :param dest_gcs: The destination Google Cloud Storage bucket and prefix
+ where you want to store the files. (templated)
+ :type dest_gcs: str
+ :param delegate_to: Google account to impersonate using domain-wide
delegation of authority,
+ if any. For this to work, the service account making the request must
have
+ domain-wide delegation enabled.
+ :type delegate_to: str
+ :param replace: Whether you want to replace existing destination files
+ or not.
+ :type replace: bool
+ :param gzip: Option to compress file for upload
+ :type gzip: bool
+ :param google_impersonation_chain: Optional Google service account to
impersonate using
+ short-term credentials, or chained list of accounts required to get
the access_token
+ of the last account in the list, which will be impersonated in the
request.
+ If set as a string, the account must grant the originating account
+ the Service Account Token Creator IAM role.
+ If set as a sequence, the identities from the list must grant
+ Service Account Token Creator IAM role to the directly preceding
identity, with first
+ account from the list granting this role to the originating account
(templated).
+ :type google_impersonation_chain: Union[str, Sequence[str]]
+
+
+ **Example**:
+
+ .. code-block:: python
+
+ azure_fileshare_to_gcs_op = AzureFileShareToGCSOperator(
+ task_id='azure_fileshare_to_gcs_example',
+ share='my-azure-share',
+ directory_name='mydir/anotherdir',
+ prefix='data/customers-201804',
+ dest_gcs_conn_id='google_cloud_default',
+ dest_gcs='gs://my.gcs.bucket/some/customers/',
+ replace=False,
+ gzip=True,
+ dag=my-dag
+ )
+
+ Note that ``share``, ``directory_name``, ``prefix``, ``delimiter`` and
``dest_gcs`` are
+ templated, so you can use variables in them if you wish.
+ """
+
+ template_fields: Iterable[str] = (
+ 'share',
+ 'directory_name',
+ 'prefix',
+ 'dest_gcs',
+ 'google_impersonation_chain',
+ )
+
+ @apply_defaults
+ def __init__(
+ self,
+ *,
+ share_name,
+ directory_name=None,
+ prefix='',
+ wasb_conn_id='wasb_default',
+ gcp_conn_id='google_cloud_default',
+ dest_gcs_conn_id=None,
+ dest_gcs=None,
+ delegate_to=None,
+ replace=False,
+ gzip=False,
+ google_impersonation_chain: Optional[Union[str, Sequence[str]]] = None,
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+
+ self.share_name = share_name
+ self.directory_name = directory_name
+ self.prefix = prefix
+ self.wasb_conn_id = wasb_conn_id
+
+ if dest_gcs_conn_id:
+ warnings.warn(
+ "The dest_gcs_conn_id parameter has been deprecated. You
should pass "
+ "the gcp_conn_id parameter.",
+ DeprecationWarning,
+ stacklevel=3,
+ )
+ gcp_conn_id = dest_gcs_conn_id
+
+ self.gcp_conn_id = gcp_conn_id
+ self.dest_gcs = dest_gcs
+ self.delegate_to = delegate_to
+ self.replace = replace
+ self.gzip = gzip
+ self.google_impersonation_chain = google_impersonation_chain
+
+ if dest_gcs and not self._gcs_object_is_directory(self.dest_gcs):
+ self.log.info(
+ 'Destination Google Cloud Storage path is not a valid '
+ '"directory", define a path that ends with a slash "/" or '
+ 'leave it empty for the root of the bucket.'
+ )
+ raise AirflowException(
+ 'The destination Google Cloud Storage path ' 'must end with a
slash "/" or be empty.'
+ )
+
+ def execute(self, context):
+ azure_fileshare_hook = AzureFileShareHook(self.wasb_conn_id)
+ files = azure_fileshare_hook.list_files(
+ share_name=self.share_name, directory_name=self.directory_name
+ )
+
+ gcs_hook = GCSHook(
+ google_cloud_storage_conn_id=self.gcp_conn_id,
+ delegate_to=self.delegate_to,
+ impersonation_chain=self.google_impersonation_chain,
+ )
+
+ # pylint: disable=too-many-nested-blocks
+ if not self.replace:
+ # if we are not replacing -> list all files in the GCS bucket
+ # and only keep those files which are present in
+ # S3 and not in Google Cloud Storage
+ bucket_name, object_prefix = _parse_gcs_url(self.dest_gcs)
+ existing_files_prefixed = gcs_hook.list(bucket_name,
prefix=object_prefix)
+
+ existing_files = []
+
+ if existing_files_prefixed:
+ # Remove the object prefix itself, an empty directory was found
+ if object_prefix in existing_files_prefixed:
+ existing_files_prefixed.remove(object_prefix)
+
+ # Remove the object prefix from all object string paths
+ for f in existing_files_prefixed:
+ if f.startswith(object_prefix):
+ existing_files.append(f[len(object_prefix) :])
+ else:
+ existing_files.append(f)
+
+ files = list(set(files) - set(existing_files))
+ if len(files) > 0:
+ self.log.info('%s files are going to be synced: %s.',
len(files), files)
+ else:
+ self.log.info('There are no new files to sync. Have a nice
day!')
+
+ if files:
+ for file in files:
+ with NamedTemporaryFile() as f:
+ azure_fileshare_hook.get_file_to_stream(
+ stream=f,
+ share_name=self.share_name,
+ directory_name=self.directory_name,
+ file_name=file,
+ )
+ f.flush()
+
+ # There will always be a '/' before file because it is
+ # enforced at instantiation time
+ dest_gcs_object = object_prefix + file
+ gcs_hook.upload(bucket_name, dest_gcs_object, f.name,
gzip=self.gzip)
+
+ self.log.info("All done, uploaded %d files to Google Cloud
Storage", len(files))
Review comment:
oops I messed identation a bit here, fixed
##########
File path: airflow/providers/google/cloud/transfers/azure_fileshare_to_gcs.py
##########
@@ -0,0 +1,217 @@
+#
+# 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 warnings
+from tempfile import NamedTemporaryFile
+from typing import Optional, Union, Sequence, Iterable
+
+from airflow import AirflowException
+from airflow.models import BaseOperator
+from airflow.providers.google.cloud.hooks.gcs import _parse_gcs_url, GCSHook
+from airflow.providers.microsoft.azure.hooks.azure_fileshare import
AzureFileShareHook
+from airflow.utils.decorators import apply_defaults
+
+
+class AzureFileShareToGCSOperator(BaseOperator):
+ """
+ Synchronizes a Azure FileShare directory content (excluding
subdirectories),
+ possibly filtered by a prefix, with a Google Cloud Storage destination
path.
+
+ :param share_name: The Azure FileShare share where to find the objects.
(templated)
+ :type share_name: str
+ :directory_name: (Optional) Path to Azure FileShare directory which
content is to be transfered.
+ Defaults to root directory (templated)
+ :param prefix: Prefix string which filters objects whose name begin with
+ such prefix. (templated)
+ :type prefix: str
+ :param wasb_conn_id: The source WASB connection
+ :type wasb_conn_id: str
+ :param gcp_conn_id: (Optional) The connection ID used to connect to Google
Cloud.
+ :type gcp_conn_id: str
+ :param dest_gcs_conn_id: (Deprecated) The connection ID used to connect to
Google Cloud.
+ This parameter has been deprecated. You should pass the gcp_conn_id
parameter instead.
+ :type dest_gcs_conn_id: str
+ :param dest_gcs: The destination Google Cloud Storage bucket and prefix
+ where you want to store the files. (templated)
+ :type dest_gcs: str
+ :param delegate_to: Google account to impersonate using domain-wide
delegation of authority,
+ if any. For this to work, the service account making the request must
have
+ domain-wide delegation enabled.
+ :type delegate_to: str
+ :param replace: Whether you want to replace existing destination files
+ or not.
+ :type replace: bool
+ :param gzip: Option to compress file for upload
+ :type gzip: bool
+ :param google_impersonation_chain: Optional Google service account to
impersonate using
+ short-term credentials, or chained list of accounts required to get
the access_token
+ of the last account in the list, which will be impersonated in the
request.
+ If set as a string, the account must grant the originating account
+ the Service Account Token Creator IAM role.
+ If set as a sequence, the identities from the list must grant
+ Service Account Token Creator IAM role to the directly preceding
identity, with first
+ account from the list granting this role to the originating account
(templated).
+ :type google_impersonation_chain: Union[str, Sequence[str]]
+
+
+ **Example**:
+
+ .. code-block:: python
+
+ azure_fileshare_to_gcs_op = AzureFileShareToGCSOperator(
+ task_id='azure_fileshare_to_gcs_example',
+ share='my-azure-share',
+ directory_name='mydir/anotherdir',
+ prefix='data/customers-201804',
+ dest_gcs_conn_id='google_cloud_default',
+ dest_gcs='gs://my.gcs.bucket/some/customers/',
+ replace=False,
+ gzip=True,
+ dag=my-dag
+ )
+
+ Note that ``share``, ``directory_name``, ``prefix``, ``delimiter`` and
``dest_gcs`` are
+ templated, so you can use variables in them if you wish.
+ """
+
+ template_fields: Iterable[str] = (
+ 'share',
+ 'directory_name',
+ 'prefix',
+ 'dest_gcs',
+ 'google_impersonation_chain',
+ )
+
+ @apply_defaults
+ def __init__(
+ self,
+ *,
+ share_name,
+ directory_name=None,
+ prefix='',
+ wasb_conn_id='wasb_default',
+ gcp_conn_id='google_cloud_default',
+ dest_gcs_conn_id=None,
+ dest_gcs=None,
+ delegate_to=None,
+ replace=False,
+ gzip=False,
+ google_impersonation_chain: Optional[Union[str, Sequence[str]]] = None,
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+
+ self.share_name = share_name
+ self.directory_name = directory_name
+ self.prefix = prefix
+ self.wasb_conn_id = wasb_conn_id
+
+ if dest_gcs_conn_id:
+ warnings.warn(
+ "The dest_gcs_conn_id parameter has been deprecated. You
should pass "
+ "the gcp_conn_id parameter.",
+ DeprecationWarning,
+ stacklevel=3,
+ )
+ gcp_conn_id = dest_gcs_conn_id
+
+ self.gcp_conn_id = gcp_conn_id
+ self.dest_gcs = dest_gcs
+ self.delegate_to = delegate_to
+ self.replace = replace
+ self.gzip = gzip
+ self.google_impersonation_chain = google_impersonation_chain
+
+ if dest_gcs and not self._gcs_object_is_directory(self.dest_gcs):
+ self.log.info(
+ 'Destination Google Cloud Storage path is not a valid '
+ '"directory", define a path that ends with a slash "/" or '
+ 'leave it empty for the root of the bucket.'
+ )
+ raise AirflowException(
+ 'The destination Google Cloud Storage path ' 'must end with a
slash "/" or be empty.'
+ )
+
+ def execute(self, context):
+ azure_fileshare_hook = AzureFileShareHook(self.wasb_conn_id)
+ files = azure_fileshare_hook.list_files(
+ share_name=self.share_name, directory_name=self.directory_name
+ )
+
+ gcs_hook = GCSHook(
+ google_cloud_storage_conn_id=self.gcp_conn_id,
+ delegate_to=self.delegate_to,
+ impersonation_chain=self.google_impersonation_chain,
+ )
+
+ # pylint: disable=too-many-nested-blocks
+ if not self.replace:
+ # if we are not replacing -> list all files in the GCS bucket
+ # and only keep those files which are present in
+ # S3 and not in Google Cloud Storage
+ bucket_name, object_prefix = _parse_gcs_url(self.dest_gcs)
+ existing_files_prefixed = gcs_hook.list(bucket_name,
prefix=object_prefix)
+
+ existing_files = []
+
+ if existing_files_prefixed:
+ # Remove the object prefix itself, an empty directory was found
+ if object_prefix in existing_files_prefixed:
+ existing_files_prefixed.remove(object_prefix)
+
+ # Remove the object prefix from all object string paths
+ for f in existing_files_prefixed:
+ if f.startswith(object_prefix):
+ existing_files.append(f[len(object_prefix) :])
+ else:
+ existing_files.append(f)
+
+ files = list(set(files) - set(existing_files))
+ if len(files) > 0:
Review comment:
fixd
##########
File path: airflow/providers/google/cloud/transfers/azure_fileshare_to_gcs.py
##########
@@ -0,0 +1,217 @@
+#
+# 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 warnings
+from tempfile import NamedTemporaryFile
+from typing import Optional, Union, Sequence, Iterable
+
+from airflow import AirflowException
+from airflow.models import BaseOperator
+from airflow.providers.google.cloud.hooks.gcs import _parse_gcs_url, GCSHook
+from airflow.providers.microsoft.azure.hooks.azure_fileshare import
AzureFileShareHook
+from airflow.utils.decorators import apply_defaults
+
+
+class AzureFileShareToGCSOperator(BaseOperator):
+ """
+ Synchronizes a Azure FileShare directory content (excluding
subdirectories),
+ possibly filtered by a prefix, with a Google Cloud Storage destination
path.
+
+ :param share_name: The Azure FileShare share where to find the objects.
(templated)
+ :type share_name: str
+ :directory_name: (Optional) Path to Azure FileShare directory which
content is to be transfered.
+ Defaults to root directory (templated)
+ :param prefix: Prefix string which filters objects whose name begin with
+ such prefix. (templated)
+ :type prefix: str
+ :param wasb_conn_id: The source WASB connection
+ :type wasb_conn_id: str
+ :param gcp_conn_id: (Optional) The connection ID used to connect to Google
Cloud.
+ :type gcp_conn_id: str
+ :param dest_gcs_conn_id: (Deprecated) The connection ID used to connect to
Google Cloud.
+ This parameter has been deprecated. You should pass the gcp_conn_id
parameter instead.
+ :type dest_gcs_conn_id: str
+ :param dest_gcs: The destination Google Cloud Storage bucket and prefix
+ where you want to store the files. (templated)
+ :type dest_gcs: str
+ :param delegate_to: Google account to impersonate using domain-wide
delegation of authority,
+ if any. For this to work, the service account making the request must
have
+ domain-wide delegation enabled.
+ :type delegate_to: str
+ :param replace: Whether you want to replace existing destination files
+ or not.
+ :type replace: bool
+ :param gzip: Option to compress file for upload
+ :type gzip: bool
+ :param google_impersonation_chain: Optional Google service account to
impersonate using
+ short-term credentials, or chained list of accounts required to get
the access_token
+ of the last account in the list, which will be impersonated in the
request.
+ If set as a string, the account must grant the originating account
+ the Service Account Token Creator IAM role.
+ If set as a sequence, the identities from the list must grant
+ Service Account Token Creator IAM role to the directly preceding
identity, with first
+ account from the list granting this role to the originating account
(templated).
+ :type google_impersonation_chain: Union[str, Sequence[str]]
+
+
+ **Example**:
+
+ .. code-block:: python
+
+ azure_fileshare_to_gcs_op = AzureFileShareToGCSOperator(
+ task_id='azure_fileshare_to_gcs_example',
+ share='my-azure-share',
+ directory_name='mydir/anotherdir',
+ prefix='data/customers-201804',
+ dest_gcs_conn_id='google_cloud_default',
+ dest_gcs='gs://my.gcs.bucket/some/customers/',
+ replace=False,
+ gzip=True,
+ dag=my-dag
+ )
+
+ Note that ``share``, ``directory_name``, ``prefix``, ``delimiter`` and
``dest_gcs`` are
+ templated, so you can use variables in them if you wish.
+ """
+
+ template_fields: Iterable[str] = (
+ 'share',
+ 'directory_name',
+ 'prefix',
+ 'dest_gcs',
+ 'google_impersonation_chain',
+ )
+
+ @apply_defaults
+ def __init__(
+ self,
+ *,
+ share_name,
+ directory_name=None,
+ prefix='',
+ wasb_conn_id='wasb_default',
+ gcp_conn_id='google_cloud_default',
+ dest_gcs_conn_id=None,
+ dest_gcs=None,
+ delegate_to=None,
+ replace=False,
+ gzip=False,
+ google_impersonation_chain: Optional[Union[str, Sequence[str]]] = None,
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+
+ self.share_name = share_name
+ self.directory_name = directory_name
+ self.prefix = prefix
+ self.wasb_conn_id = wasb_conn_id
+
+ if dest_gcs_conn_id:
+ warnings.warn(
+ "The dest_gcs_conn_id parameter has been deprecated. You
should pass "
+ "the gcp_conn_id parameter.",
+ DeprecationWarning,
+ stacklevel=3,
+ )
+ gcp_conn_id = dest_gcs_conn_id
+
+ self.gcp_conn_id = gcp_conn_id
+ self.dest_gcs = dest_gcs
+ self.delegate_to = delegate_to
+ self.replace = replace
+ self.gzip = gzip
+ self.google_impersonation_chain = google_impersonation_chain
+
+ if dest_gcs and not self._gcs_object_is_directory(self.dest_gcs):
+ self.log.info(
+ 'Destination Google Cloud Storage path is not a valid '
+ '"directory", define a path that ends with a slash "/" or '
+ 'leave it empty for the root of the bucket.'
+ )
+ raise AirflowException(
+ 'The destination Google Cloud Storage path ' 'must end with a
slash "/" or be empty.'
Review comment:
true, fixd
##########
File path: airflow/providers/google/cloud/transfers/azure_fileshare_to_gcs.py
##########
@@ -0,0 +1,217 @@
+#
+# 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 warnings
+from tempfile import NamedTemporaryFile
+from typing import Optional, Union, Sequence, Iterable
+
+from airflow import AirflowException
+from airflow.models import BaseOperator
+from airflow.providers.google.cloud.hooks.gcs import _parse_gcs_url, GCSHook
+from airflow.providers.microsoft.azure.hooks.azure_fileshare import
AzureFileShareHook
+from airflow.utils.decorators import apply_defaults
+
+
+class AzureFileShareToGCSOperator(BaseOperator):
+ """
+ Synchronizes a Azure FileShare directory content (excluding
subdirectories),
+ possibly filtered by a prefix, with a Google Cloud Storage destination
path.
+
+ :param share_name: The Azure FileShare share where to find the objects.
(templated)
+ :type share_name: str
+ :directory_name: (Optional) Path to Azure FileShare directory which
content is to be transfered.
+ Defaults to root directory (templated)
+ :param prefix: Prefix string which filters objects whose name begin with
+ such prefix. (templated)
+ :type prefix: str
+ :param wasb_conn_id: The source WASB connection
+ :type wasb_conn_id: str
+ :param gcp_conn_id: (Optional) The connection ID used to connect to Google
Cloud.
+ :type gcp_conn_id: str
+ :param dest_gcs_conn_id: (Deprecated) The connection ID used to connect to
Google Cloud.
+ This parameter has been deprecated. You should pass the gcp_conn_id
parameter instead.
+ :type dest_gcs_conn_id: str
+ :param dest_gcs: The destination Google Cloud Storage bucket and prefix
+ where you want to store the files. (templated)
+ :type dest_gcs: str
+ :param delegate_to: Google account to impersonate using domain-wide
delegation of authority,
+ if any. For this to work, the service account making the request must
have
+ domain-wide delegation enabled.
+ :type delegate_to: str
+ :param replace: Whether you want to replace existing destination files
+ or not.
+ :type replace: bool
+ :param gzip: Option to compress file for upload
+ :type gzip: bool
+ :param google_impersonation_chain: Optional Google service account to
impersonate using
+ short-term credentials, or chained list of accounts required to get
the access_token
+ of the last account in the list, which will be impersonated in the
request.
+ If set as a string, the account must grant the originating account
+ the Service Account Token Creator IAM role.
+ If set as a sequence, the identities from the list must grant
+ Service Account Token Creator IAM role to the directly preceding
identity, with first
+ account from the list granting this role to the originating account
(templated).
+ :type google_impersonation_chain: Union[str, Sequence[str]]
+
+
+ **Example**:
+
+ .. code-block:: python
+
+ azure_fileshare_to_gcs_op = AzureFileShareToGCSOperator(
+ task_id='azure_fileshare_to_gcs_example',
+ share='my-azure-share',
+ directory_name='mydir/anotherdir',
+ prefix='data/customers-201804',
+ dest_gcs_conn_id='google_cloud_default',
+ dest_gcs='gs://my.gcs.bucket/some/customers/',
+ replace=False,
+ gzip=True,
+ dag=my-dag
+ )
+
+ Note that ``share``, ``directory_name``, ``prefix``, ``delimiter`` and
``dest_gcs`` are
+ templated, so you can use variables in them if you wish.
+ """
+
+ template_fields: Iterable[str] = (
+ 'share',
+ 'directory_name',
+ 'prefix',
+ 'dest_gcs',
+ 'google_impersonation_chain',
+ )
+
+ @apply_defaults
+ def __init__(
+ self,
+ *,
+ share_name,
+ directory_name=None,
+ prefix='',
+ wasb_conn_id='wasb_default',
+ gcp_conn_id='google_cloud_default',
+ dest_gcs_conn_id=None,
+ dest_gcs=None,
+ delegate_to=None,
+ replace=False,
+ gzip=False,
+ google_impersonation_chain: Optional[Union[str, Sequence[str]]] = None,
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+
+ self.share_name = share_name
+ self.directory_name = directory_name
+ self.prefix = prefix
+ self.wasb_conn_id = wasb_conn_id
+
+ if dest_gcs_conn_id:
+ warnings.warn(
+ "The dest_gcs_conn_id parameter has been deprecated. You
should pass "
+ "the gcp_conn_id parameter.",
+ DeprecationWarning,
+ stacklevel=3,
+ )
+ gcp_conn_id = dest_gcs_conn_id
+
+ self.gcp_conn_id = gcp_conn_id
+ self.dest_gcs = dest_gcs
+ self.delegate_to = delegate_to
+ self.replace = replace
+ self.gzip = gzip
+ self.google_impersonation_chain = google_impersonation_chain
+
+ if dest_gcs and not self._gcs_object_is_directory(self.dest_gcs):
+ self.log.info(
+ 'Destination Google Cloud Storage path is not a valid '
+ '"directory", define a path that ends with a slash "/" or '
+ 'leave it empty for the root of the bucket.'
+ )
+ raise AirflowException(
+ 'The destination Google Cloud Storage path ' 'must end with a
slash "/" or be empty.'
+ )
+
+ def execute(self, context):
+ azure_fileshare_hook = AzureFileShareHook(self.wasb_conn_id)
+ files = azure_fileshare_hook.list_files(
+ share_name=self.share_name, directory_name=self.directory_name
+ )
+
+ gcs_hook = GCSHook(
+ google_cloud_storage_conn_id=self.gcp_conn_id,
+ delegate_to=self.delegate_to,
+ impersonation_chain=self.google_impersonation_chain,
+ )
+
+ # pylint: disable=too-many-nested-blocks
+ if not self.replace:
+ # if we are not replacing -> list all files in the GCS bucket
+ # and only keep those files which are present in
+ # S3 and not in Google Cloud Storage
+ bucket_name, object_prefix = _parse_gcs_url(self.dest_gcs)
+ existing_files_prefixed = gcs_hook.list(bucket_name,
prefix=object_prefix)
+
+ existing_files = []
+
+ if existing_files_prefixed:
+ # Remove the object prefix itself, an empty directory was found
+ if object_prefix in existing_files_prefixed:
+ existing_files_prefixed.remove(object_prefix)
+
+ # Remove the object prefix from all object string paths
+ for f in existing_files_prefixed:
+ if f.startswith(object_prefix):
+ existing_files.append(f[len(object_prefix) :])
+ else:
+ existing_files.append(f)
+
+ files = list(set(files) - set(existing_files))
+ if len(files) > 0:
+ self.log.info('%s files are going to be synced: %s.',
len(files), files)
+ else:
+ self.log.info('There are no new files to sync. Have a nice
day!')
+
+ if files:
+ for file in files:
Review comment:
I believe that main purpose of this `if` is to make it possible to
decide which message should be logged - either "All done (...)" or "In sync, no
files needed (...)" - however I agree that its a good idea to remove this `if`
from here and place it directly over the messages.
##########
File path: airflow/providers/google/cloud/transfers/azure_fileshare_to_gcs.py
##########
@@ -0,0 +1,217 @@
+#
+# 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 warnings
+from tempfile import NamedTemporaryFile
+from typing import Optional, Union, Sequence, Iterable
+
+from airflow import AirflowException
+from airflow.models import BaseOperator
+from airflow.providers.google.cloud.hooks.gcs import _parse_gcs_url, GCSHook
+from airflow.providers.microsoft.azure.hooks.azure_fileshare import
AzureFileShareHook
+from airflow.utils.decorators import apply_defaults
+
+
+class AzureFileShareToGCSOperator(BaseOperator):
+ """
+ Synchronizes a Azure FileShare directory content (excluding
subdirectories),
+ possibly filtered by a prefix, with a Google Cloud Storage destination
path.
+
+ :param share_name: The Azure FileShare share where to find the objects.
(templated)
+ :type share_name: str
+ :directory_name: (Optional) Path to Azure FileShare directory which
content is to be transfered.
+ Defaults to root directory (templated)
+ :param prefix: Prefix string which filters objects whose name begin with
+ such prefix. (templated)
+ :type prefix: str
+ :param wasb_conn_id: The source WASB connection
+ :type wasb_conn_id: str
+ :param gcp_conn_id: (Optional) The connection ID used to connect to Google
Cloud.
+ :type gcp_conn_id: str
+ :param dest_gcs_conn_id: (Deprecated) The connection ID used to connect to
Google Cloud.
+ This parameter has been deprecated. You should pass the gcp_conn_id
parameter instead.
+ :type dest_gcs_conn_id: str
+ :param dest_gcs: The destination Google Cloud Storage bucket and prefix
+ where you want to store the files. (templated)
+ :type dest_gcs: str
+ :param delegate_to: Google account to impersonate using domain-wide
delegation of authority,
+ if any. For this to work, the service account making the request must
have
+ domain-wide delegation enabled.
+ :type delegate_to: str
+ :param replace: Whether you want to replace existing destination files
+ or not.
+ :type replace: bool
+ :param gzip: Option to compress file for upload
+ :type gzip: bool
+ :param google_impersonation_chain: Optional Google service account to
impersonate using
+ short-term credentials, or chained list of accounts required to get
the access_token
+ of the last account in the list, which will be impersonated in the
request.
+ If set as a string, the account must grant the originating account
+ the Service Account Token Creator IAM role.
+ If set as a sequence, the identities from the list must grant
+ Service Account Token Creator IAM role to the directly preceding
identity, with first
+ account from the list granting this role to the originating account
(templated).
+ :type google_impersonation_chain: Union[str, Sequence[str]]
+
+
+ **Example**:
+
+ .. code-block:: python
+
+ azure_fileshare_to_gcs_op = AzureFileShareToGCSOperator(
+ task_id='azure_fileshare_to_gcs_example',
+ share='my-azure-share',
+ directory_name='mydir/anotherdir',
+ prefix='data/customers-201804',
+ dest_gcs_conn_id='google_cloud_default',
+ dest_gcs='gs://my.gcs.bucket/some/customers/',
+ replace=False,
+ gzip=True,
+ dag=my-dag
+ )
+
+ Note that ``share``, ``directory_name``, ``prefix``, ``delimiter`` and
``dest_gcs`` are
+ templated, so you can use variables in them if you wish.
+ """
+
+ template_fields: Iterable[str] = (
Review comment:
indeed fixd
##########
File path: airflow/providers/google/cloud/transfers/azure_fileshare_to_gcs.py
##########
@@ -0,0 +1,217 @@
+#
+# 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 warnings
+from tempfile import NamedTemporaryFile
+from typing import Optional, Union, Sequence, Iterable
+
+from airflow import AirflowException
+from airflow.models import BaseOperator
+from airflow.providers.google.cloud.hooks.gcs import _parse_gcs_url, GCSHook
+from airflow.providers.microsoft.azure.hooks.azure_fileshare import
AzureFileShareHook
+from airflow.utils.decorators import apply_defaults
+
+
+class AzureFileShareToGCSOperator(BaseOperator):
+ """
+ Synchronizes a Azure FileShare directory content (excluding
subdirectories),
+ possibly filtered by a prefix, with a Google Cloud Storage destination
path.
+
+ :param share_name: The Azure FileShare share where to find the objects.
(templated)
+ :type share_name: str
+ :directory_name: (Optional) Path to Azure FileShare directory which
content is to be transfered.
+ Defaults to root directory (templated)
+ :param prefix: Prefix string which filters objects whose name begin with
+ such prefix. (templated)
+ :type prefix: str
+ :param wasb_conn_id: The source WASB connection
+ :type wasb_conn_id: str
+ :param gcp_conn_id: (Optional) The connection ID used to connect to Google
Cloud.
+ :type gcp_conn_id: str
+ :param dest_gcs_conn_id: (Deprecated) The connection ID used to connect to
Google Cloud.
+ This parameter has been deprecated. You should pass the gcp_conn_id
parameter instead.
+ :type dest_gcs_conn_id: str
+ :param dest_gcs: The destination Google Cloud Storage bucket and prefix
+ where you want to store the files. (templated)
+ :type dest_gcs: str
+ :param delegate_to: Google account to impersonate using domain-wide
delegation of authority,
+ if any. For this to work, the service account making the request must
have
+ domain-wide delegation enabled.
+ :type delegate_to: str
+ :param replace: Whether you want to replace existing destination files
+ or not.
+ :type replace: bool
+ :param gzip: Option to compress file for upload
+ :type gzip: bool
+ :param google_impersonation_chain: Optional Google service account to
impersonate using
+ short-term credentials, or chained list of accounts required to get
the access_token
+ of the last account in the list, which will be impersonated in the
request.
+ If set as a string, the account must grant the originating account
+ the Service Account Token Creator IAM role.
+ If set as a sequence, the identities from the list must grant
+ Service Account Token Creator IAM role to the directly preceding
identity, with first
+ account from the list granting this role to the originating account
(templated).
+ :type google_impersonation_chain: Union[str, Sequence[str]]
+
+
+ **Example**:
Review comment:
fixd
##########
File path: tests/providers/microsoft/azure/hooks/test_azure_fileshare.py
##########
@@ -112,6 +113,20 @@ def test_list_directories_and_files(self, mock_service):
hook.list_directories_and_files('share', 'directory', timeout=1)
mock_instance.list_directories_and_files.assert_called_once_with('share',
'directory', timeout=1)
+
@mock.patch('airflow.providers.microsoft.azure.hooks.azure_fileshare.FileService',
autospec=True)
+ def test_list_files(self, mock_service):
+ mock_instance = mock_service.return_value
+ mock_instance.list_directories_and_files.return_value = [
+ File("file1"),
+ File("file2"),
+ Directory("dir1"),
+ Directory("dir2"),
+ ]
+ hook = AzureFileShareHook(wasb_conn_id='wasb_test_sas_token')
+ files = hook.list_files('share', 'directory', timeout=1)
Review comment:
its not - `list_files` is a wrapper around original
`list_files_and_directories` api call which makes the original call and then
filters out directories from results list, therefore mocking
`FileService.list_files_and_directories` is enough
##########
File path: tests/providers/microsoft/azure/hooks/test_azure_fileshare.py
##########
@@ -112,6 +113,20 @@ def test_list_directories_and_files(self, mock_service):
hook.list_directories_and_files('share', 'directory', timeout=1)
mock_instance.list_directories_and_files.assert_called_once_with('share',
'directory', timeout=1)
+
@mock.patch('airflow.providers.microsoft.azure.hooks.azure_fileshare.FileService',
autospec=True)
+ def test_list_files(self, mock_service):
+ mock_instance = mock_service.return_value
+ mock_instance.list_directories_and_files.return_value = [
+ File("file1"),
+ File("file2"),
+ Directory("dir1"),
+ Directory("dir2"),
+ ]
+ hook = AzureFileShareHook(wasb_conn_id='wasb_test_sas_token')
+ files = hook.list_files('share', 'directory', timeout=1)
Review comment:
its not - `list_files` is a wrapper around
`AzureFileShareHook.list_files_and_directories` api call which makes the
original call (`FileService.list_files_and_directories`) and then filters out
directories from results list, therefore mocking
`FileService.list_files_and_directories` is enough
##########
File path: airflow/providers/google/cloud/transfers/azure_fileshare_to_gcs.py
##########
@@ -0,0 +1,209 @@
+#
+# 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 tempfile import NamedTemporaryFile
+from typing import Optional, Union, Sequence, Iterable
+
+from airflow import AirflowException
+from airflow.models import BaseOperator
+from airflow.providers.google.cloud.hooks.gcs import _parse_gcs_url, GCSHook
+from airflow.providers.microsoft.azure.hooks.azure_fileshare import
AzureFileShareHook
+from airflow.utils.decorators import apply_defaults
+
+
+class AzureFileShareToGCSOperator(BaseOperator):
+ """
+ Synchronizes a Azure FileShare directory content (excluding
subdirectories),
+ possibly filtered by a prefix, with a Google Cloud Storage destination
path.
+
+ :param share_name: The Azure FileShare share where to find the objects.
(templated)
+ :type share_name: str
+ :directory_name: (Optional) Path to Azure FileShare directory which
content is to be transfered.
+ Defaults to root directory (templated)
Review comment:
yes, fixd
##########
File path: docs/howto/operator/google/transfer/azure_fileshare_to_gcs.rst
##########
@@ -0,0 +1,54 @@
+ .. 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.
+
+Transfers data from Azure FileShare Storage to Google Cloud Storage
+============================================================
Review comment:
indeed
##########
File path: tests/providers/google/cloud/transfers/test_azure_fileshare_to_gcs.py
##########
@@ -0,0 +1,121 @@
+# 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 unittest
+
+import mock
+
+from airflow.providers.google.cloud.transfers.azure_fileshare_to_gcs import
AzureFileShareToGCSOperator
+
+TASK_ID = 'test-azure-fileshare-to-gcs'
+AZURE_FILESHARE_SHARE = 'test-share'
+AZURE_FILESHARE_DIRECTORY_NAME = '/path/to/dir'
+GCS_PATH_PREFIX = 'gs://gcs-bucket/data/'
+MOCK_FILES = ["TEST1.csv", "TEST2.csv", "TEST3.csv"]
+WASB_CONN_ID = 'wasb_default'
+GCS_CONN_ID = 'google_cloud_default'
+IMPERSONATION_CHAIN = ["ACCOUNT_1", "ACCOUNT_2", "ACCOUNT_3"]
+
+
+class TestAzureFileShareToGCSOperator(unittest.TestCase):
+ def test_init(self):
+ """Test AzureFileShareToGCSOperator instance is properly
initialized."""
+
+ operator = AzureFileShareToGCSOperator(
+ task_id=TASK_ID,
+ share_name=AZURE_FILESHARE_SHARE,
+ directory_name=AZURE_FILESHARE_DIRECTORY_NAME,
+ wasb_conn_id=WASB_CONN_ID,
+ gcp_conn_id=GCS_CONN_ID,
+ dest_gcs=GCS_PATH_PREFIX,
+ google_impersonation_chain=IMPERSONATION_CHAIN,
+ )
+
+ self.assertEqual(operator.task_id, TASK_ID)
+ self.assertEqual(operator.share_name, AZURE_FILESHARE_SHARE)
+ self.assertEqual(operator.directory_name,
AZURE_FILESHARE_DIRECTORY_NAME)
+ self.assertEqual(operator.wasb_conn_id, WASB_CONN_ID)
+ self.assertEqual(operator.gcp_conn_id, GCS_CONN_ID)
+ self.assertEqual(operator.dest_gcs, GCS_PATH_PREFIX)
+ self.assertEqual(operator.google_impersonation_chain,
IMPERSONATION_CHAIN)
+
+
@mock.patch('airflow.providers.google.cloud.transfers.azure_fileshare_to_gcs.AzureFileShareHook')
+
@mock.patch('airflow.providers.google.cloud.transfers.azure_fileshare_to_gcs.GCSHook')
+ def test_execute(self, gcs_mock_hook, azure_fileshare_mock_hook):
+ """Test the execute function when the run is successful."""
+
+ operator = AzureFileShareToGCSOperator(
+ task_id=TASK_ID,
+ share_name=AZURE_FILESHARE_SHARE,
+ directory_name=AZURE_FILESHARE_DIRECTORY_NAME,
+ wasb_conn_id=WASB_CONN_ID,
+ gcp_conn_id=GCS_CONN_ID,
+ dest_gcs=GCS_PATH_PREFIX,
+ google_impersonation_chain=IMPERSONATION_CHAIN,
+ )
+
+ azure_fileshare_mock_hook.return_value.list_files.return_value =
MOCK_FILES
+
+ uploaded_files = operator.execute(None)
+
+ gcs_mock_hook.return_value.upload.assert_has_calls(
+ [
+ mock.call('gcs-bucket', 'data/TEST1.csv', mock.ANY,
gzip=False),
+ mock.call('gcs-bucket', 'data/TEST3.csv', mock.ANY,
gzip=False),
+ mock.call('gcs-bucket', 'data/TEST2.csv', mock.ANY,
gzip=False),
+ ],
+ any_order=True,
+ )
+
+ azure_fileshare_mock_hook.assert_called_once_with(WASB_CONN_ID)
+
+ gcs_mock_hook.assert_called_once_with(
+ google_cloud_storage_conn_id=GCS_CONN_ID,
+ delegate_to=None,
+ impersonation_chain=IMPERSONATION_CHAIN,
+ )
+
+ self.assertEqual(sorted(MOCK_FILES), sorted(uploaded_files))
+
+
@mock.patch('airflow.providers.google.cloud.transfers.azure_fileshare_to_gcs.AzureFileShareHook')
+
@mock.patch('airflow.providers.google.cloud.transfers.azure_fileshare_to_gcs.GCSHook')
+ def test_execute_with_gzip(self, gcs_mock_hook, azure_fileshare_mock_hook):
+ """Test the execute function when the run is successful."""
+
+ operator = AzureFileShareToGCSOperator(
+ task_id=TASK_ID,
+ share_name=AZURE_FILESHARE_SHARE,
+ directory_name=AZURE_FILESHARE_DIRECTORY_NAME,
+ wasb_conn_id=WASB_CONN_ID,
+ gcp_conn_id=GCS_CONN_ID,
+ dest_gcs=GCS_PATH_PREFIX,
+ google_impersonation_chain=IMPERSONATION_CHAIN,
+ gzip=True,
+ )
+
+ azure_fileshare_mock_hook.return_value.list_files.return_value =
MOCK_FILES
+
+ operator.execute(None)
+
+ gcs_mock_hook.return_value.upload.assert_has_calls(
Review comment:
thanks ^^
##########
File path: airflow/providers/google/cloud/transfers/azure_fileshare_to_gcs.py
##########
@@ -0,0 +1,209 @@
+#
+# 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 tempfile import NamedTemporaryFile
+from typing import Optional, Union, Sequence, Iterable
+
+from airflow import AirflowException
+from airflow.models import BaseOperator
+from airflow.providers.google.cloud.hooks.gcs import _parse_gcs_url, GCSHook
+from airflow.providers.microsoft.azure.hooks.azure_fileshare import
AzureFileShareHook
+from airflow.utils.decorators import apply_defaults
+
+
+class AzureFileShareToGCSOperator(BaseOperator):
+ """
+ Synchronizes a Azure FileShare directory content (excluding
subdirectories),
+ possibly filtered by a prefix, with a Google Cloud Storage destination
path.
+
+ :param share_name: The Azure FileShare share where to find the objects.
(templated)
+ :type share_name: str
+ :directory_name: (Optional) Path to Azure FileShare directory which
content is to be transfered.
+ Defaults to root directory (templated)
+ :param prefix: Prefix string which filters objects whose name begin with
+ such prefix. (templated)
+ :type prefix: str
+ :param wasb_conn_id: The source WASB connection
+ :type wasb_conn_id: str
+ :param gcp_conn_id: (Optional) The connection ID used to connect to Google
Cloud.
+ :type gcp_conn_id: str
+ :param dest_gcs_conn_id: (Deprecated) The connection ID used to connect to
Google Cloud.
+ This parameter has been deprecated. You should pass the gcp_conn_id
parameter instead.
+ :type dest_gcs_conn_id: str
+ :param dest_gcs: The destination Google Cloud Storage bucket and prefix
+ where you want to store the files. (templated)
+ :type dest_gcs: str
+ :param delegate_to: Google account to impersonate using domain-wide
delegation of authority,
+ if any. For this to work, the service account making the request must
have
+ domain-wide delegation enabled.
+ :type delegate_to: str
+ :param replace: Whether you want to replace existing destination files
+ or not.
+ :type replace: bool
+ :param gzip: Option to compress file for upload
+ :type gzip: bool
+ :param google_impersonation_chain: Optional Google service account to
impersonate using
+ short-term credentials, or chained list of accounts required to get
the access_token
+ of the last account in the list, which will be impersonated in the
request.
+ If set as a string, the account must grant the originating account
+ the Service Account Token Creator IAM role.
+ If set as a sequence, the identities from the list must grant
+ Service Account Token Creator IAM role to the directly preceding
identity, with first
+ account from the list granting this role to the originating account
(templated).
+ :type google_impersonation_chain: Union[str, Sequence[str]]
+
+
+ **Example**:
+
+ .. code-block:: python
+
+ azure_fileshare_to_gcs_op = AzureFileShareToGCSOperator(
+ task_id='azure_fileshare_to_gcs_example',
+ share_name='my-azure-share',
+ directory_name='mydir/anotherdir',
+ prefix='data/customers-201804',
+ wasb_conn_id='azure_fileshare_default',
+ gcp_conn_id='google_cloud_default',
+ dest_gcs='gs://my.gcs.bucket/some/customers/',
+ replace=False,
+ gzip=True,
+ google_impersonation_chain=['account1', 'account2', 'account3'],
+ dag=my-dag
+ )
+
+ Note that ``share_name``, ``directory_name``, ``prefix``, ``delimiter``
and ``dest_gcs`` are
+ templated, so you can use variables in them if you wish.
+ """
+
+ template_fields: Iterable[str] = (
+ 'share_name',
+ 'directory_name',
+ 'prefix',
+ 'dest_gcs',
+ 'google_impersonation_chain',
+ )
+
+ @apply_defaults
+ def __init__(
+ self,
+ *,
+ share_name,
+ directory_name=None,
+ prefix='',
+ wasb_conn_id='wasb_default',
+ gcp_conn_id='google_cloud_default',
+ dest_gcs=None,
+ delegate_to=None,
+ replace=False,
+ gzip=False,
+ google_impersonation_chain: Optional[Union[str, Sequence[str]]] = None,
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+
+ self.share_name = share_name
+ self.directory_name = directory_name
+ self.prefix = prefix
+ self.wasb_conn_id = wasb_conn_id
+ self.gcp_conn_id = gcp_conn_id
+ self.dest_gcs = dest_gcs
+ self.delegate_to = delegate_to
+ self.replace = replace
+ self.gzip = gzip
+ self.google_impersonation_chain = google_impersonation_chain
+
+ if dest_gcs and not self._gcs_object_is_directory(self.dest_gcs):
+ self.log.info(
+ 'Destination Google Cloud Storage path is not a valid '
+ '"directory", define a path that ends with a slash "/" or '
+ 'leave it empty for the root of the bucket.'
+ )
+ raise AirflowException(
+ 'The destination Google Cloud Storage path must end with a
slash "/" or be empty.'
+ )
+
+ def execute(self, context):
+ azure_fileshare_hook = AzureFileShareHook(self.wasb_conn_id)
+ files = azure_fileshare_hook.list_files(
+ share_name=self.share_name, directory_name=self.directory_name
+ )
+
+ gcs_hook = GCSHook(
+ google_cloud_storage_conn_id=self.gcp_conn_id,
+ delegate_to=self.delegate_to,
+ impersonation_chain=self.google_impersonation_chain,
+ )
+
+ dest_gcs_bucket, dest_gcs_object_prefix = _parse_gcs_url(self.dest_gcs)
+
+ # pylint: disable=too-many-nested-blocks
+ if not self.replace:
+ # if we are not replacing -> list all files in the GCS bucket
+ # and only keep those files which are present in
+ # S3 and not in Google Cloud Storage
+ existing_files_prefixed = gcs_hook.list(dest_gcs_bucket,
prefix=dest_gcs_object_prefix)
+
+ existing_files = []
+
+ if existing_files_prefixed:
+ # Remove the object prefix itself, an empty directory was found
+ if dest_gcs_object_prefix in existing_files_prefixed:
+ existing_files_prefixed.remove(dest_gcs_object_prefix)
+
+ # Remove the object prefix from all object string paths
+ for f in existing_files_prefixed:
+ if f.startswith(dest_gcs_object_prefix):
+ existing_files.append(f[len(dest_gcs_object_prefix) :])
+ else:
+ existing_files.append(f)
+
+ files = list(set(files) - set(existing_files))
+ if files:
+ self.log.info('%s files are going to be synced: %s.',
len(files), files)
+ else:
+ self.log.info('There are no new files to sync. Have a nice
day!')
Review comment:
^^
##########
File path:
airflow/providers/microsoft/azure/example_dags/example_azure_fileshare_to_gcs.py
##########
@@ -0,0 +1,52 @@
+# 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 datetime import timedelta, datetime
+
+from airflow import DAG
+from airflow.providers.google.cloud.transfers.azure_fileshare_to_gcs import
AzureFileShareToGCSOperator
+
+default_args = {
+ 'owner': 'airflow',
+ 'depends_on_past': False,
+ 'email': ['[email protected]'],
+ 'email_on_failure': False,
+ 'email_on_retry': False,
+ 'retries': 1,
+ 'retry_delay': timedelta(minutes=5),
+}
+
+with DAG(
+ dag_id='aci_example',
+ default_args=default_args,
+ schedule_interval=timedelta(1),
+ start_date=datetime(2018, 11, 1),
+ tags=['example'],
+) as dag:
+
+ t1 = AzureFileShareToGCSOperator(
Review comment:
indeed
##########
File path:
airflow/providers/microsoft/azure/example_dags/example_azure_fileshare_to_gcs.py
##########
@@ -0,0 +1,52 @@
+# 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 datetime import timedelta, datetime
+
+from airflow import DAG
+from airflow.providers.google.cloud.transfers.azure_fileshare_to_gcs import
AzureFileShareToGCSOperator
+
+default_args = {
+ 'owner': 'airflow',
+ 'depends_on_past': False,
+ 'email': ['[email protected]'],
+ 'email_on_failure': False,
+ 'email_on_retry': False,
+ 'retries': 1,
+ 'retry_delay': timedelta(minutes=5),
+}
+
+with DAG(
+ dag_id='aci_example',
+ default_args=default_args,
+ schedule_interval=timedelta(1),
+ start_date=datetime(2018, 11, 1),
+ tags=['example'],
+) as dag:
+
+ t1 = AzureFileShareToGCSOperator(
+ task_id='sync_azure_files_with_gcs',
+ share_name='my-azure-share',
+ directory_name='mydir/anotherdir',
+ prefix='data/customers-201804',
+ wasb_conn_id='azure_fileshare_default',
+ gcp_conn_id='google_cloud_default',
+ dest_gcs='gs://my.gcs.bucket/some/customers/',
+ replace=False,
+ gzip=True,
+ google_impersonation_chain=['account1', 'account2', 'account3'],
+ )
Review comment:
yes
##########
File path: tests/providers/google/cloud/transfers/test_azure_fileshare_to_gcs.py
##########
@@ -0,0 +1,121 @@
+# 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 unittest
+
+import mock
+
+from airflow.providers.google.cloud.transfers.azure_fileshare_to_gcs import
AzureFileShareToGCSOperator
+
+TASK_ID = 'test-azure-fileshare-to-gcs'
+AZURE_FILESHARE_SHARE = 'test-share'
+AZURE_FILESHARE_DIRECTORY_NAME = '/path/to/dir'
+GCS_PATH_PREFIX = 'gs://gcs-bucket/data/'
+MOCK_FILES = ["TEST1.csv", "TEST2.csv", "TEST3.csv"]
+WASB_CONN_ID = 'wasb_default'
+GCS_CONN_ID = 'google_cloud_default'
+IMPERSONATION_CHAIN = ["ACCOUNT_1", "ACCOUNT_2", "ACCOUNT_3"]
+
+
+class TestAzureFileShareToGCSOperator(unittest.TestCase):
+ def test_init(self):
Review comment:
thanks
----------------------------------------------------------------
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:
[email protected]