-
Notifications
You must be signed in to change notification settings - Fork 13.7k
/
cloud_storage_transfer_service.py
839 lines (707 loc) · 31 KB
/
cloud_storage_transfer_service.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
#
# 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.
#
"""
This module contains Google Cloud Transfer operators.
"""
from copy import deepcopy
from datetime import date, time
from typing import Dict, Optional
from airflow.exceptions import AirflowException
from airflow.models import BaseOperator
from airflow.providers.amazon.aws.hooks.base_aws import AwsBaseHook
from airflow.providers.google.cloud.hooks.cloud_storage_transfer_service import (
ACCESS_KEY_ID, AWS_ACCESS_KEY, AWS_S3_DATA_SOURCE, BUCKET_NAME, DAY, DESCRIPTION, GCS_DATA_SINK,
GCS_DATA_SOURCE, HOURS, HTTP_DATA_SOURCE, MINUTES, MONTH, OBJECT_CONDITIONS, PROJECT_ID, SCHEDULE,
SCHEDULE_END_DATE, SCHEDULE_START_DATE, SECONDS, SECRET_ACCESS_KEY, START_TIME_OF_DAY, STATUS,
TRANSFER_OPTIONS, TRANSFER_SPEC, YEAR, CloudDataTransferServiceHook, GcpTransferJobsStatus,
)
from airflow.utils.decorators import apply_defaults
class TransferJobPreprocessor:
"""
Helper class for preprocess of transfer job body.
"""
def __init__(self, body: dict, aws_conn_id: str = 'aws_default', default_schedule: bool = False) -> None:
self.body = body
self.aws_conn_id = aws_conn_id
self.default_schedule = default_schedule
def _inject_aws_credentials(self):
if TRANSFER_SPEC in self.body and AWS_S3_DATA_SOURCE in self.body[TRANSFER_SPEC]:
aws_hook = AwsBaseHook(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[TRANSFER_SPEC][AWS_S3_DATA_SOURCE][AWS_ACCESS_KEY] = {
ACCESS_KEY_ID: aws_access_key_id,
SECRET_ACCESS_KEY: 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:
if self.default_schedule:
self.body[SCHEDULE] = {
SCHEDULE_START_DATE: date.today(),
SCHEDULE_END_DATE: date.today()
}
else:
return
self._reformat_date(SCHEDULE_START_DATE)
self._reformat_date(SCHEDULE_END_DATE)
self._reformat_time(START_TIME_OF_DAY)
def process_body(self):
"""
Injects AWS credentials into body if needed and
reformats schedule information.
:return: Preprocessed body
:rtype: dict
"""
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_object):
"""
Convert native python ``datetime.time`` object to a format supported by the API
"""
return {HOURS: time_object.hour, MINUTES: time_object.minute, SECONDS: time_object.second}
class TransferJobValidator:
"""
Helper class for validating transfer job body.
"""
def __init__(self, body: dict) -> None:
if not body:
raise AirflowException("The required parameter 'body' is empty or None")
self.body = body
def _verify_data_source(self):
is_gcs = GCS_DATA_SOURCE in self.body[TRANSFER_SPEC]
is_aws_s3 = AWS_S3_DATA_SOURCE in self.body[TRANSFER_SPEC]
is_http = HTTP_DATA_SOURCE in self.body[TRANSFER_SPEC]
sources_count = sum([is_gcs, is_aws_s3, is_http])
if 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):
aws_transfer = AWS_S3_DATA_SOURCE in self.body[TRANSFER_SPEC]
if aws_transfer and AWS_ACCESS_KEY in self.body[TRANSFER_SPEC][AWS_S3_DATA_SOURCE]:
raise AirflowException(
"AWS credentials detected inside the body parameter (awsAccessKey). This is not allowed, "
"please use Airflow connections to store credentials."
)
def validate_body(self):
"""
Validates the body. Checks if body specifies `transferSpec`
if yes, then check if AWS credentials are passed correctly and
no more than 1 data source was selected.
:raises: AirflowException
"""
if TRANSFER_SPEC in self.body:
self._restrict_aws_credentials()
self._verify_data_source()
class CloudDataTransferServiceCreateJobOperator(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:CloudDataTransferServiceCreateJobOperator`
: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: dict,
aws_conn_id: str = 'aws_default',
gcp_conn_id: str = 'google_cloud_default',
api_version: str = 'v1',
*args,
**kwargs
) -> None:
super().__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 = CloudDataTransferServiceHook(api_version=self.api_version, gcp_conn_id=self.gcp_conn_id)
return hook.create_transfer_job(body=self.body)
class CloudDataTransferServiceUpdateJobOperator(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:CloudDataTransferServiceUpdateJobOperator`
: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: str,
body: dict,
aws_conn_id: str = 'aws_default',
gcp_conn_id: str = 'google_cloud_default',
api_version: str = 'v1',
*args,
**kwargs
) -> None:
super().__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 = CloudDataTransferServiceHook(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 CloudDataTransferServiceDeleteJobOperator(BaseOperator):
"""
Delete a transfer job. This is a soft delete. After a transfer job is
deleted, the job and all the transfer executions are subject to garbage
collection. Transfer jobs become eligible for garbage collection
30 days after soft delete.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudDataTransferServiceDeleteJobOperator`
: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', 'api_version')
# [END gcp_transfer_job_delete_template_fields]
@apply_defaults
def __init__(
self,
job_name: str,
gcp_conn_id: str = "google_cloud_default",
api_version: str = "v1",
project_id: Optional[str] = None,
*args,
**kwargs
) -> None:
super().__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 = CloudDataTransferServiceHook(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 CloudDataTransferServiceGetOperationOperator(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:CloudDataTransferServiceGetOperationOperator`
: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: str,
gcp_conn_id: str = "google_cloud_default",
api_version: str = "v1",
*args,
**kwargs
) -> None:
super().__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 = CloudDataTransferServiceHook(api_version=self.api_version, gcp_conn_id=self.gcp_conn_id)
operation = hook.get_transfer_operation(operation_name=self.operation_name)
return operation
class CloudDataTransferServiceListOperationsOperator(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:CloudDataTransferServiceListOperationsOperator`
:param request_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 request_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,
request_filter: Optional[Dict] = None,
gcp_conn_id: str = 'google_cloud_default',
api_version: str = 'v1',
*args,
**kwargs) -> None:
# To preserve backward compatibility
# TODO: remove one day
if request_filter is None:
if 'filter' in kwargs:
request_filter = kwargs['filter']
DeprecationWarning("Use 'request_filter' instead 'filter' to pass the argument.")
else:
TypeError("__init__() missing 1 required positional argument: 'request_filter'")
super().__init__(*args, **kwargs)
self.filter = request_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 = CloudDataTransferServiceHook(api_version=self.api_version, gcp_conn_id=self.gcp_conn_id)
operations_list = hook.list_transfer_operations(request_filter=self.filter)
self.log.info(operations_list)
return operations_list
class CloudDataTransferServicePauseOperationOperator(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:CloudDataTransferServicePauseOperationOperator`
: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', 'api_version')
# [END gcp_transfer_operation_pause_template_fields]
@apply_defaults
def __init__(
self,
operation_name: str,
gcp_conn_id: str = "google_cloud_default",
api_version: str = "v1",
*args,
**kwargs
) -> None:
super().__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 = CloudDataTransferServiceHook(api_version=self.api_version, gcp_conn_id=self.gcp_conn_id)
hook.pause_transfer_operation(operation_name=self.operation_name)
class CloudDataTransferServiceResumeOperationOperator(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:CloudDataTransferServiceResumeOperationOperator`
: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: str,
gcp_conn_id: str = "google_cloud_default",
api_version: str = "v1",
*args,
**kwargs
) -> None:
self.operation_name = operation_name
self.gcp_conn_id = gcp_conn_id
self.api_version = api_version
self._validate_inputs()
super().__init__(*args, **kwargs)
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 = CloudDataTransferServiceHook(api_version=self.api_version, gcp_conn_id=self.gcp_conn_id)
hook.resume_transfer_operation(operation_name=self.operation_name)
class CloudDataTransferServiceCancelOperationOperator(BaseOperator):
"""
Cancels 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:CloudDataTransferServiceCancelOperationOperator`
:param operation_name: (Required) Name of the transfer operation.
:type operation_name: str
:param api_version: API version used (e.g. v1).
:type api_version: str
:param gcp_conn_id: The connection ID used to connect to Google
Cloud Platform.
:type gcp_conn_id: str
"""
# [START gcp_transfer_operation_cancel_template_fields]
template_fields = ('operation_name', 'gcp_conn_id', 'api_version')
# [END gcp_transfer_operation_cancel_template_fields]
@apply_defaults
def __init__(
self,
operation_name: str,
gcp_conn_id: str = "google_cloud_default",
api_version: str = "v1",
*args,
**kwargs
) -> None:
super().__init__(*args, **kwargs)
self.operation_name = operation_name
self.api_version = api_version
self.gcp_conn_id = gcp_conn_id
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 = CloudDataTransferServiceHook(api_version=self.api_version, gcp_conn_id=self.gcp_conn_id)
hook.cancel_transfer_operation(operation_name=self.operation_name)
class CloudDataTransferServiceS3ToGCSOperator(BaseOperator):
"""
Synchronizes an S3 bucket with a Google Cloud Storage bucket using the
GCP Storage Transfer Service.
.. warning::
This operator is NOT idempotent. If you run it many times, many transfer
jobs will be created in the Google Cloud Platform.
**Example**:
.. code-block:: python
s3_to_gcs_transfer_op = S3ToGoogleCloudStorageTransferOperator(
task_id='s3_to_gcs_transfer_example',
s3_bucket='my-s3-bucket',
project_id='my-gcp-project',
gcs_bucket='my-gcs-bucket',
dag=my_dag)
:param s3_bucket: The S3 bucket where to find the objects. (templated)
:type s3_bucket: str
:param gcs_bucket: The destination Google Cloud Storage bucket
where you want to store the files. (templated)
:type gcs_bucket: str
:param project_id: Optional ID of the Google Cloud Platform Console project that
owns the job
:type project_id: str
:param aws_conn_id: The source S3 connection
:type aws_conn_id: str
:param gcp_conn_id: The destination connection ID to use
when connecting to Google Cloud Storage.
:type gcp_conn_id: str
:param delegate_to: The account to impersonate, if any.
For this to work, the service account making the request must have
domain-wide delegation enabled.
:type delegate_to: str
:param description: Optional transfer service job description
:type description: str
:param schedule: Optional transfer service schedule;
If not set, run transfer job once as soon as the operator runs
The format is described
https://cloud.google.com/storage-transfer/docs/reference/rest/v1/transferJobs.
With two additional improvements:
* dates they can be passed as :class:`datetime.date`
* times they can be passed as :class:`datetime.time`
:type schedule: dict
:param object_conditions: Optional transfer service object conditions; see
https://cloud.google.com/storage-transfer/docs/reference/rest/v1/TransferSpec
:type object_conditions: dict
:param transfer_options: Optional transfer service transfer options; see
https://cloud.google.com/storage-transfer/docs/reference/rest/v1/TransferSpec
:type transfer_options: dict
:param wait: Wait for transfer to finish
:type wait: bool
:param timeout: Time to wait for the operation to end in seconds. Defaults to 60 seconds if not specified.
:type timeout: Optional[Union[float, timedelta]]
"""
template_fields = ('gcp_conn_id', 's3_bucket', 'gcs_bucket', 'description', 'object_conditions')
ui_color = '#e09411'
@apply_defaults
def __init__( # pylint: disable=too-many-arguments
self,
s3_bucket: str,
gcs_bucket: str,
project_id: Optional[str] = None,
aws_conn_id: str = 'aws_default',
gcp_conn_id: str = 'google_cloud_default',
delegate_to: Optional[str] = None,
description: Optional[str] = None,
schedule: Optional[Dict] = None,
object_conditions: Optional[Dict] = None,
transfer_options: Optional[Dict] = None,
wait: bool = True,
timeout: Optional[float] = None,
*args,
**kwargs
) -> None:
super().__init__(*args, **kwargs)
self.s3_bucket = s3_bucket
self.gcs_bucket = gcs_bucket
self.project_id = project_id
self.aws_conn_id = aws_conn_id
self.gcp_conn_id = gcp_conn_id
self.delegate_to = delegate_to
self.description = description
self.schedule = schedule
self.object_conditions = object_conditions
self.transfer_options = transfer_options
self.wait = wait
self.timeout = timeout
def execute(self, context):
hook = CloudDataTransferServiceHook(gcp_conn_id=self.gcp_conn_id, delegate_to=self.delegate_to)
body = self._create_body()
TransferJobPreprocessor(body=body, aws_conn_id=self.aws_conn_id, default_schedule=True).process_body()
job = hook.create_transfer_job(body=body)
if self.wait:
hook.wait_for_transfer_job(job, timeout=self.timeout)
def _create_body(self):
body = {
DESCRIPTION: self.description,
STATUS: GcpTransferJobsStatus.ENABLED,
TRANSFER_SPEC: {
AWS_S3_DATA_SOURCE: {BUCKET_NAME: self.s3_bucket},
GCS_DATA_SINK: {BUCKET_NAME: self.gcs_bucket},
},
}
if self.project_id is not None:
body[PROJECT_ID] = self.project_id
if self.schedule is not None:
body[SCHEDULE] = self.schedule
if self.object_conditions is not None:
body[TRANSFER_SPEC][OBJECT_CONDITIONS] = self.object_conditions
if self.transfer_options is not None:
body[TRANSFER_SPEC][TRANSFER_OPTIONS] = self.transfer_options
return body
class CloudDataTransferServiceGCSToGCSOperator(BaseOperator):
"""
Copies objects from a bucket to another using the GCP Storage Transfer
Service.
.. 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:GCSToGCSOperator`
**Example**:
.. code-block:: python
gcs_to_gcs_transfer_op = GoogleCloudStorageToGoogleCloudStorageTransferOperator(
task_id='gcs_to_gcs_transfer_example',
source_bucket='my-source-bucket',
destination_bucket='my-destination-bucket',
project_id='my-gcp-project',
dag=my_dag)
:param source_bucket: The source Google Cloud Storage bucket where the
object is. (templated)
:type source_bucket: str
:param destination_bucket: The destination Google Cloud Storage bucket
where the object should be. (templated)
:type destination_bucket: str
:param project_id: The ID of the Google Cloud Platform Console project that
owns the job
:type project_id: str
:param gcp_conn_id: Optional connection ID to use when connecting to Google Cloud
Storage.
:type gcp_conn_id: str
:param delegate_to: The account to impersonate, if any.
For this to work, the service account making the request must have
domain-wide delegation enabled.
:type delegate_to: str
:param description: Optional transfer service job description
:type description: str
:param schedule: Optional transfer service schedule;
If not set, run transfer job once as soon as the operator runs
See:
https://cloud.google.com/storage-transfer/docs/reference/rest/v1/transferJobs.
With two additional improvements:
* dates they can be passed as :class:`datetime.date`
* times they can be passed as :class:`datetime.time`
:type schedule: dict
:param object_conditions: Optional transfer service object conditions; see
https://cloud.google.com/storage-transfer/docs/reference/rest/v1/TransferSpec#ObjectConditions
:type object_conditions: dict
:param transfer_options: Optional transfer service transfer options; see
https://cloud.google.com/storage-transfer/docs/reference/rest/v1/TransferSpec#TransferOptions
:type transfer_options: dict
:param wait: Wait for transfer to finish; defaults to `True`
:type wait: bool
:param timeout: Time to wait for the operation to end in seconds. Defaults to 60 seconds if not specified.
:type timeout: Optional[Union[float, timedelta]]
"""
template_fields = (
'gcp_conn_id',
'source_bucket',
'destination_bucket',
'description',
'object_conditions',
)
ui_color = '#e09411'
@apply_defaults
def __init__( # pylint: disable=too-many-arguments
self,
source_bucket: str,
destination_bucket: str,
project_id: Optional[str] = None,
gcp_conn_id: str = 'google_cloud_default',
delegate_to: Optional[str] = None,
description: Optional[str] = None,
schedule: Optional[Dict] = None,
object_conditions: Optional[Dict] = None,
transfer_options: Optional[Dict] = None,
wait: bool = True,
timeout: Optional[float] = None,
*args,
**kwargs
) -> None:
super().__init__(*args, **kwargs)
self.source_bucket = source_bucket
self.destination_bucket = destination_bucket
self.project_id = project_id
self.gcp_conn_id = gcp_conn_id
self.delegate_to = delegate_to
self.description = description
self.schedule = schedule
self.object_conditions = object_conditions
self.transfer_options = transfer_options
self.wait = wait
self.timeout = timeout
def execute(self, context):
hook = CloudDataTransferServiceHook(gcp_conn_id=self.gcp_conn_id, delegate_to=self.delegate_to)
body = self._create_body()
TransferJobPreprocessor(body=body, default_schedule=True).process_body()
job = hook.create_transfer_job(body=body)
if self.wait:
hook.wait_for_transfer_job(job, timeout=self.timeout)
def _create_body(self):
body = {
DESCRIPTION: self.description,
STATUS: GcpTransferJobsStatus.ENABLED,
TRANSFER_SPEC: {
GCS_DATA_SOURCE: {BUCKET_NAME: self.source_bucket},
GCS_DATA_SINK: {BUCKET_NAME: self.destination_bucket},
},
}
if self.project_id is not None:
body[PROJECT_ID] = self.project_id
if self.schedule is not None:
body[SCHEDULE] = self.schedule
if self.object_conditions is not None:
body[TRANSFER_SPEC][OBJECT_CONDITIONS] = self.object_conditions
if self.transfer_options is not None:
body[TRANSFER_SPEC][TRANSFER_OPTIONS] = self.transfer_options
return body