-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathautomated-migration-to-s3-tables-latest.yaml
2001 lines (1810 loc) · 81.3 KB
/
automated-migration-to-s3-tables-latest.yaml
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
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
AWSTemplateFormatVersion: 2010-09-09
Description: An Amazon S3 Tables Bucket Migration Solution (SO9586).
Metadata:
Version: '1.0.0'
License:
Description: >-
'MIT No Attribution
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.'
AWS::CloudFormation::Interface:
ParameterGroups:
-
Label:
default: "Source Amazon S3 General Purpose Bucket, Glue Database and Table details"
Parameters:
- YourS3Bucket
- YourExistingGlueDatabase
- YourExistingGlueTable
- YourExistingTableType
-
Label:
default: "Destination Amazon S3 Table Bucket ARN, Namespace, Table and Table Partitions"
Parameters:
- S3TableBucket
- S3TableBucketNamespace
- S3TableBucketTables
- S3TableBucketTablesPartitions
-
Label:
default: "Please choose your desired Migration Type"
Parameters:
- MigrationType
-
Label:
default: "Job Notification and Tracking"
Parameters:
- RecipientEmail
-
Label:
default: "EMR Cluster Performance"
Parameters:
- ClusterSize
-
Label:
default: "EMR Instance Networking and Primary Node Keypair"
Parameters:
- subnetIDs
- KeyPair
ParameterLabels:
YourS3Bucket:
default: "The source Amazon S3 Bucket containing your table data"
S3TableBucket:
default: "Your destination Amazon S3 Table Bucket ARN"
S3TableBucketTables:
default: "Your destination table name in S3 Table Bucket"
S3TableBucketNamespace:
default: "Your destination namespace in S3 Table Bucket"
S3TableBucketTablesPartitions:
default: "Desired partition(s) in your destination table"
YourExistingGlueDatabase:
default: "The source Glue Data Catalog database name"
YourExistingGlueTable:
default: "The source Glue Data Catalog table name"
MigrationType:
default: "Migration type"
YourExistingTableType:
default: "The source Glue Data Catalog table format for example Standard(Hive) or Iceberg"
RecipientEmail:
default: "Email address to receive job notifications"
ClusterSize:
default: "Your desired EMR EC2 Cluster Size"
subnetIDs:
default: "VPC Subnet to deploy the EMR Cluster"
KeyPair:
default: "EC2 keypair for the EMR Cluster primary instance"
Parameters:
YourS3Bucket:
Description: Please enter the name of the bucket containing the table data you want to migrate
Type: String
AllowedPattern: '^[a-z0-9.-]{3,63}$'
ConstraintDescription: Bucket name must contain only lowercase letters, numbers, periods (.), and dashes (-). Visit Amazon S3 User Guide 'https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html'
S3TableBucket:
Description: Please enter the ARN of your S3 table bucket
Type: String
MinLength: '3'
ConstraintDescription: Please provide your desired valid S3 table bucket ARN
AllowedPattern: '(arn:aws[-a-z0-9]*:[a-z0-9]+:[-a-z0-9]*:[0-9]{12}:bucket/[a-z0-9_-]{3,63})'
S3TableBucketNamespace:
Description: Please specify the S3 table Namespace where your data will be stored in your table bucket
Type: String
MinLength: '1'
MaxLength: '1024'
ConstraintDescription: Please provide your desired namespace
AllowedPattern: '[0-9a-z_]*'
S3TableBucketTables:
Description: Please enter your desired destination table name
Type: String
MinLength: '1'
MaxLength: '63'
ConstraintDescription: Please provide your desired destination table name
AllowedPattern: '[0-9a-z_]*'
S3TableBucketTablesPartitions:
Description: Please enter your desired table partitions. Valid partition keys are (col1) for single column partition or (col1, col2) for multiple column partitions. Do not include partition column types!
Type: String
Default: NotApplicable
ConstraintDescription: Please provide your desired destination partition information in the format (col1) or (col1, col2 ...) or type NotApplicable
MinLength: '3'
AllowedPattern: ^(NotApplicable|\([^)]*\))
YourExistingGlueDatabase:
Description: Please specify your source Glue database name
Type: String
MinLength: '1'
MaxLength: '255'
ConstraintDescription: Please provide your existing Glue Database name or Namespace
AllowedPattern: '[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\t]*'
YourExistingGlueTable:
Description: Please specify your existing Glue table name
Type: String
MinLength: '1'
MaxLength: '255'
ConstraintDescription: Please provide your existing Glue table name
AllowedPattern: '[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\t]*'
YourExistingTableType:
AllowedValues:
- Standard
- Iceberg
Description: Please specify your source Glue table format, for example Standard or Iceberg
Type: String
Default: Standard
ConstraintDescription: Please provide your existing Glue table format
ClusterSize:
Description: Please choose the size of your EMR Cluster to meet the desired migration workload
Type: String
Default: Small
AllowedValues:
- Small
- Medium
- Large
- Xlarge
ConstraintDescription: Cluster Size must be within the allowed value
MigrationType:
AllowedValues:
- New-Migration
Description: New-Migration use CTAS [Create Table As Select] to migrate table from S3 general purpose bucket to a new Amazon S3 table bucket
Type: String
Default: New-Migration
RecipientEmail:
Description: Please enter the email address to receive Job notifications. Please remember to Confirm the SNS subscription
Type: String
MinLength: '5'
MaxLength: '150'
ConstraintDescription: Please enter a valid email address
AllowedPattern: '^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$'
subnetIDs:
Description: Please choose exactly two Subnets, EMR will evaluate and deploy into only one of the subnets. Please review [https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-clusters-in-a-vpc.html].
Type: List<AWS::EC2::Subnet::Id>
MinLength: '1'
ConstraintDescription: Please specify exactly two SubnetIDs
KeyPair:
Type: 'AWS::EC2::KeyPair::KeyName'
Description: Please choose a KeyPair to enable SSH Access into the EMR Cluster Nodes.
MinLength: '1'
ConstraintDescription: Please specify an EC2 Keypair name
Mappings:
PySpark:
Script:
s3key: resources/script/mys3tablespysparkscript.py
csvwithversionid: restore-and-copy/csv-manifest/with-version-id/
Parameter:
catalogname: s3tablescatalog
sparkcatalog: mysparkcatalog
EMR:
Cluster:
releaselabel: emr-7.5.0
Small:
PrimaryInstanceCount: 1
PrimaryInstanceType: m5.4xlarge
PrimaryInstanceType2: m5d.4xlarge
CoreInstanceCount: 1
CoreInstanceType: i3.4xlarge
CoreInstanceType2: r5d.4xlarge
TaskInstanceCount: 1
TaskInstanceType: i3.4xlarge
TaskInstanceType2: r5d.4xlarge
executorMemory: 24G
executorCores: 4
driverMemory: 24G
driverCores: 4
dynamicAllocMaxExec: 7
executorMemoryOverhead: 8G
driverMemoryOverhead: 2G
driverMaxResultsSize: 4G
DiskSize: 64
PryNodeDiskCount: 2
CoreNodeDiskCount: 4
TaskNodeDiskCount: 3
Medium:
PrimaryInstanceCount: 1
PrimaryInstanceType: m5.4xlarge
PrimaryInstanceType2: m5d.4xlarge
CoreInstanceCount: 4
CoreInstanceType: i3.4xlarge
CoreInstanceType2: r5d.4xlarge
TaskInstanceCount: 4
TaskInstanceType: i3.4xlarge
TaskInstanceType2: r5d.4xlarge
executorMemory: 24G
executorCores: 4
driverMemory: 24G
driverCores: 4
dynamicAllocMaxExec: 29
executorMemoryOverhead: 8G
driverMemoryOverhead: 2G
driverMaxResultsSize: 4G
DiskSize: 64
PryNodeDiskCount: 2
CoreNodeDiskCount: 4
TaskNodeDiskCount: 3
Large:
PrimaryInstanceCount: 1
PrimaryInstanceType: r5.4xlarge
PrimaryInstanceType2: i3.4xlarge
CoreInstanceCount: 4
CoreInstanceType: i3.4xlarge
CoreInstanceType2: r5d.4xlarge
TaskInstanceCount: 8
TaskInstanceType: i3.4xlarge
TaskInstanceType2: r5d.4xlarge
executorMemory: 24G
executorCores: 3
driverMemory: 32G
driverCores: 4
dynamicAllocMaxExec: 44
executorMemoryOverhead: 8G
driverMemoryOverhead: 6G
driverMaxResultsSize: 12G
DiskSize: 128
PryNodeDiskCount: 2
CoreNodeDiskCount: 4
TaskNodeDiskCount: 3
Xlarge:
PrimaryInstanceCount: 1
PrimaryInstanceType: r5.4xlarge
PrimaryInstanceType2: i3.4xlarge
CoreInstanceCount: 8
CoreInstanceType: i3.4xlarge
CoreInstanceType2: r5d.4xlarge
TaskInstanceCount: 12
TaskInstanceType: i3.4xlarge
TaskInstanceType2: r5d.4xlarge
executorMemory: 28G
executorCores: 4
driverMemory: 48G
driverCores: 4
dynamicAllocMaxExec: 74
executorMemoryOverhead: 8G
driverMemoryOverhead: 6G
driverMaxResultsSize: 16G
DiskSize: 256
PryNodeDiskCount: 3
CoreNodeDiskCount: 4
TaskNodeDiskCount: 3
Performance:
Parameters:
sdkretryattempts: 10
Resources:
Topic:
DependsOn:
- CheckResourceExists
Type: AWS::SNS::Topic
Properties:
KmsMasterKeyId: alias/aws/sns
TopicSubscription:
DependsOn:
- CheckResourceExists
Type: AWS::SNS::Subscription
Properties:
Endpoint: !Ref RecipientEmail
Protocol: email
TopicArn: !Ref Topic
################################## Custom Resources ##############################################################
################################ CheckResourceExists ######################################################
CheckResourceExists:
DependsOn:
- CheckTableLFAccess
- CheckDBLFAccess
Type: 'Custom::LambdaTrigger'
Properties:
ServiceToken: !GetAtt CheckResourceExistsLambdaFunction.Arn
bucketexists: !Ref YourS3Bucket
sourcetableexists: !Ref YourExistingGlueTable
sourcedbexists: !Ref YourExistingGlueDatabase
CheckTableLFAccess:
Type: AWS::LakeFormation::PrincipalPermissions
Properties:
Principal:
DataLakePrincipalIdentifier: !GetAtt CheckResourceExistsIAMRole.Arn
Resource:
Table:
CatalogId: !Sub ${AWS::AccountId}
DatabaseName: !Ref YourExistingGlueDatabase
Name: !Ref YourExistingGlueTable
Permissions:
- "SELECT"
- "DESCRIBE"
PermissionsWithGrantOption:
- "SELECT"
- "DESCRIBE"
CheckDBLFAccess:
Type: AWS::LakeFormation::PrincipalPermissions
Properties:
Principal:
DataLakePrincipalIdentifier: !GetAtt CheckResourceExistsIAMRole.Arn
Resource:
Database:
CatalogId: !Sub ${AWS::AccountId}
Name: !Ref YourExistingGlueDatabase
Permissions:
- "DESCRIBE"
PermissionsWithGrantOption:
- "DESCRIBE"
CheckResourceExistsIAMRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- 'sts:AssumeRole'
Path: /
Policies:
- PolicyName: AWSLambdaBasicExecutionRole
PolicyDocument:
Version: "2012-10-17"
Statement:
- Action:
- 'logs:CreateLogGroup'
- 'logs:CreateLogStream'
- 'logs:PutLogEvents'
Resource: !Sub 'arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:*'
Effect: Allow
- PolicyName: CheckBucketExistsPermissions
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- 's3:GetBucketLocation'
Resource: !Sub arn:${AWS::Partition}:s3:::${YourS3Bucket}
- PolicyName: CheckSourceTableExistsPermissions
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- glue:GetTable
- glue:GetTables
Resource:
- !Sub "arn:${AWS::Partition}:glue:${AWS::Region}:${AWS::AccountId}:table/${YourExistingGlueDatabase}/${YourExistingGlueTable}"
- !Sub "arn:${AWS::Partition}:glue:${AWS::Region}:${AWS::AccountId}:database/${YourExistingGlueDatabase}"
- !Sub "arn:${AWS::Partition}:glue:${AWS::Region}:${AWS::AccountId}:catalog"
CheckResourceExistsLambdaFunction:
Type: 'AWS::Lambda::Function'
Properties:
Architectures:
- arm64
Handler: index.lambda_handler
Role: !GetAtt CheckResourceExistsIAMRole.Arn
Runtime: python3.12
Timeout: 150
MemorySize: 128
Code:
ZipFile: |
import json
import cfnresponse
import logging
import os
import boto3
from botocore.exceptions import ClientError
from botocore.client import Config
# Enable debugging for troubleshooting
# boto3.set_stream_logger("")
# Set up logging
logger = logging.getLogger(__name__)
logger.setLevel('INFO')
# Define Environmental Variables
my_region = str(os.environ['AWS_REGION'])
# Set SDK paramters
config = Config(retries = {'max_attempts': 5})
# Set variables
# Set Service Parameters
s3Client = boto3.client('s3', config=config, region_name=my_region)
glueClient = boto3.client('glue', region_name=my_region)
def get_table(db_name, tbl_name):
logger.info(f"Checking if Source Glue Table Exists")
try:
check_table = glueClient.get_table(
DatabaseName=db_name,
Name=tbl_name,
)
except Exception as e:
logger.error(e)
raise e
else:
logger.info(check_table.get('Table').get('Name'))
logger.info(f"Table {tbl_name} exists!")
return check_table
def check_bucket_exists(bucket):
logger.info(f"Checking if Source Bucket Exists")
try:
check_bucket = s3Client.get_bucket_location(
Bucket=bucket,
)
except ClientError as e:
logger.error(e)
raise
else:
logger.info(f"Bucket {bucket}, exists, proceeding with deployment ...")
return check_bucket
def lambda_handler(event, context):
# Define Environmental Variables
s3Bucket = event.get('ResourceProperties').get('bucketexists')
gluedb = event.get('ResourceProperties').get('sourcedbexists')
gluetbl = event.get('ResourceProperties').get('sourcetableexists')
logger.info(f'Event detail is: {event}')
if event.get('RequestType') == 'Create':
# logger.info(event)
try:
logger.info("Stack event is Create, checking specified Source S3 Bucket and Source Glue Table exists...")
if s3Bucket:
check_bucket_exists(s3Bucket)
get_table(gluedb, gluetbl)
responseData = {}
responseData['message'] = "Successful"
logger.info(f"Sending Invocation Response {responseData['message']} to Cloudformation Service")
cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData)
except Exception as e:
logger.error(e)
responseData = {}
responseData['message'] = str(e)
failure_reason = str(e)
logger.info(f"Sending Invocation Response {responseData['message']} to Cloudformation Service")
cfnresponse.send(event, context, cfnresponse.FAILED, responseData, reason=failure_reason)
elif event.get('RequestType') == 'Delete' or event.get('RequestType') == 'Update':
logger.info(event)
try:
logger.info(f"Stack event is Delete or Update, nothing to do....")
responseData = {}
responseData['message'] = "Completed"
logger.info(f"Sending Invocation Response {responseData['message']} to Cloudformation Service")
cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData)
except Exception as e:
logger.error(e)
responseData = {}
responseData['message'] = str(e)
logger.info(f"Sending Invocation Response {responseData['message']} to Cloudformation Service")
cfnresponse.send(event, context, cfnresponse.FAILED, responseData)
################################################ Code Ends ####################################################
EMRLogS3Bucket:
DependsOn:
- CheckResourceExists
Type: 'AWS::S3::Bucket'
DeletionPolicy: Retain
UpdateReplacePolicy: Retain
Properties:
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
LifecycleConfiguration:
Rules:
- Id: ExpirationRule
Prefix: logs/
Status: Enabled
ExpirationInDays: 180
NoncurrentVersionExpiration:
NoncurrentDays: 3
- Id: delete-incomplete-mpu
Status: Enabled
AbortIncompleteMultipartUpload:
DaysAfterInitiation: 1
############################################################ Upload PySpark Script to S3 Bucket ###################################################
UploadScriptCustomResource:
DependsOn:
- CheckResourceExists
Type: Custom::EmptyS3Bucket
Properties:
ServiceToken: !GetAtt UploadScriptFunction.Arn
UploadScriptFunctionIAMRole:
DependsOn:
- CheckResourceExists
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Principal:
Service:
- "lambda.amazonaws.com"
Action:
- "sts:AssumeRole"
Path: '/'
Policies:
- PolicyName: AWSLambdaBasicExecutionRole
PolicyDocument:
Version: "2012-10-17"
Statement:
- Action:
- 'logs:CreateLogGroup'
- 'logs:CreateLogStream'
- 'logs:PutLogEvents'
Resource: !Sub 'arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:*'
Effect: Allow
- PolicyName: WriteObjectPolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- 's3:PutObject*'
- 's3:List*'
- 's3:GetObject*'
Resource:
- !Sub arn:${AWS::Partition}:s3:::${EMRLogS3Bucket}/*
- !Sub arn:${AWS::Partition}:s3:::${EMRLogS3Bucket}
UploadScriptFunction:
DependsOn:
- CheckResourceExists
Type: 'AWS::Lambda::Function'
Properties:
Architectures:
- arm64
Environment:
Variables:
asset1: !FindInMap [ PySpark, Script, s3key ]
my_account_id: !Sub ${AWS::AccountId}
s3BuckettoDownload: !Ref EMRLogS3Bucket
max_attempts: !FindInMap [ Performance, Parameters, sdkretryattempts ]
asset1_key: !FindInMap [ PySpark, Script, s3key ]
Description: Downloads Function Source Code from Github to S3
MemorySize: 384
Runtime: python3.12
Handler: index.lambda_handler
Role: !GetAtt UploadScriptFunctionIAMRole.Arn
Timeout: 360
Code:
ZipFile: |
import cfnresponse
import boto3
import io
import json
import logging
import uuid
import os
from botocore.client import Config
from botocore.exceptions import ClientError
from boto3.s3.transfer import TransferConfig
# Enable Debug logging
boto3.set_stream_logger('')
# Setup Logging
logger = logging.getLogger(__name__)
logger.setLevel('INFO')
# Define Environmental Variables
my_asset1_key = str(os.environ['asset1_key'])
my_bucket = str(os.environ['s3BuckettoDownload'])
my_max_attempts = int(os.environ['max_attempts'])
my_region = str(os.environ['AWS_REGION'])
# Set and Declare Configuration Parameters
config = Config(retries={'max_attempts': my_max_attempts})
# Set Service Clients
s3 = boto3.resource('s3', config=config)
# Upload PySpark Script to Solution S3 Bucket
def stream_to_s3(bucket, key, body):
logger.info(f'Starting PySpark Script upload to the S3 Bucket: s3://{bucket}/{key}')
try:
upload_to_s3 = s3.Object(bucket, key).put(Body=body)
except Exception as e:
logger.error(e)
else:
logger.info(f'Object successfully uploaded to s3://{bucket}/{key}')
# Define PySpark Script to Upload as blob
my_blob = f'''
import sys
import argparse
from pyspark.sql import SparkSession
from pyspark import SparkConf
import logging
# Setup Logging
logger = logging.getLogger(__name__)
logger.setLevel('INFO')
# Import Sys Arguments
parser = argparse.ArgumentParser()
parser.add_argument('--data_migration_type', help="Data Migration type new or insert/update.")
parser.add_argument('--data_source_bucket', help="Source data S3 bucket name.")
parser.add_argument('--data_source_db', help="Source data Glue Database name.")
parser.add_argument('--data_source_tbl', help="Source data Glue Table name.")
parser.add_argument('--data_source_type', help="Source data Glue Table Type.")
parser.add_argument('--data_source_catalog', help="Source DB/TableCatalog.")
parser.add_argument('--data_destination_s3tables_arn', help="Destination S3 Table ARN.")
parser.add_argument('--data_destination_catalog', help="Destination S3 Tables Catalog.")
parser.add_argument('--data_destination_s3tables_namespace', help="Destination S3 Tables Namespace/Database.")
parser.add_argument('--data_destination_s3tables_tbl', help="Destination S3 Tables Table name .")
parser.add_argument('--data_destination_s3tables_partitions', help="Destination S3 Tables Table Partitions .")
# Initiate ARGS
args = parser.parse_args()
# Now define the variables
data_migration_type = args.data_migration_type
data_source_bucket = args.data_source_bucket
data_source_db = args.data_source_db
data_source_tbl = args.data_source_tbl
data_source_type = args.data_source_type
data_source_catalog = args.data_source_catalog
data_destination_catalog = args.data_destination_catalog
data_destination_s3tables_arn = args.data_destination_s3tables_arn
data_destination_s3tables_namespace = args.data_destination_s3tables_namespace
data_destination_s3tables_tbl = args.data_destination_s3tables_tbl
data_destination_s3tables_partitions = args.data_destination_s3tables_partitions
# Create Spark Configuration Set
conf = SparkConf() \
.set("spark.sql.catalogImplementation", "hive") \
.set("mapreduce.input.fileinputformat.input.dir.recursive", "true") \
.set(f"spark.sql.catalog.{{data_destination_catalog}}", "org.apache.iceberg.spark.SparkCatalog") \
.set(f"spark.sql.extensions", "org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions") \
.set(f"spark.sql.catalog.{{data_destination_catalog}}.catalog-impl", "software.amazon.s3tables.iceberg.S3TablesCatalog") \
.set(f"spark.sql.catalog.{{data_destination_catalog}}.io-impl", "org.apache.iceberg.aws.s3.S3FileIO") \
.set(f"spark.sql.catalog.{{data_destination_catalog}}.warehouse", data_destination_s3tables_arn) \
.set(f"spark.sql.catalog.{{data_source_catalog}}", "org.apache.iceberg.spark.SparkCatalog") \
.set(f"spark.sql.catalog.{{data_source_catalog}}.catalog-impl", "org.apache.iceberg.aws.glue.GlueCatalog") \
.set(f"spark.sql.catalog.{{data_source_catalog}}.io-impl", "org.apache.iceberg.aws.s3.S3FileIO")
# Initiate PySpark Session
spark = SparkSession.builder.appName("MyMigrationApp").config(conf=conf).getOrCreate()
# Function for creating a New NameSpace in Amazon S3 Table Bucket
def create_namespace(catalog, dst_db):
# Create a NameSpace in S3 Table Buckets first
try:
# Create the Namespace first
sql_query_namespace = f"""
CREATE NAMESPACE IF NOT EXISTS
`{{catalog}}`.`{{dst_db}}`
"""
# Now run the query
spark_sql_query_namespace = spark.sql(sql_query_namespace)
except Exception as e:
print(e)
raise e
# Function for performing INSERT/UPDATE into an existing destination Database/Table
def insert_update_action(src_catalog, catalog, src_db, src_tbl, dst_db, dst_tbl):
"""
Use INSERT/UPDATE to load data from source to S3 Tables Bucket
:param:
"""
try:
# Do an INSERT INTO to migrate table data from source to S3 Tables Bucket
sql_query_insert = ''
# Let's start the INSERT INTO action FOR the earlier CTAS
print(f"Initiating INSERT INTO worklow from {{src_catalog}}.{{src_db}}.{{src_tbl}} into {{dst_db}}.{{dst_tbl}} please hold...")
# Handle query with or without catalog name provided
if src_catalog:
sql_query_insert = f"""
INSERT INTO
`{{catalog}}`.`{{dst_db}}`.`{{dst_tbl}}`
SELECT * FROM `{{src_catalog}}`.`{{src_db}}`.`{{src_tbl}}`
"""
else:
sql_query_insert = f"""
INSERT INTO
`{{catalog}}`.`{{dst_db}}`.`{{dst_tbl}}`
SELECT * FROM `{{src_db}}`.`{{src_tbl}}`
"""
# Run the INSERT INTO SQL query
spark_sql_query_insert = spark.sql(sql_query_insert)
except Exception as e:
print(e)
raise e
else:
print(f"INSERT INTO worklow from {{src_db}}.{{src_tbl}} into {{dst_db}}.{{dst_tbl}} completed!")
# Function for performing CTAS - CREATE TABLE AS SELECT into a new destination Database/Table - creates a new DB/Table
def ctas_action(src_catalog, catalog, src_db, src_tbl, dst_db, dst_tbl, dst_partitions):
"""
Use CTAS to load data from source to S3 Tables Bucket
:param:
"""
print(f"Echo parameters src_catalog={{src_catalog}}, catalog={{catalog}}, src_db={{src_db}}, src_tbl={{src_tbl}}, dst_db={{dst_db}}, dst_tbl={{dst_tbl}}")
# We need to create the namespace/database first, so calling the namespace function
print(f"Creating the namespace {{dst_db}} first if it does not already exist....")
create_namespace(catalog, dst_db)
print(f"Creating the namespace {{dst_db}} is successful proceeding to CTAS, please hold...")
try:
# Do a CTAS to migrate table data from source Table to S3 Tables Bucket
# If destination partition is provided, them include partition info in CTAS query
# We are not loading data now, just creating an empty table
sql_query_d = ''
# Check the provided partition name and value for the destination Table
if dst_partitions:
if dst_partitions == "NotApplicable":
# Handle query with or without catalog name provided
if src_catalog:
sql_query_d = f"""
CREATE TABLE IF NOT EXISTS
`{{catalog}}`.`{{dst_db}}`.`{{dst_tbl}}`
USING iceberg
AS SELECT * FROM `{{src_catalog}}`.`{{src_db}}`.`{{src_tbl}}`
LIMIT 0
"""
else:
sql_query_d = f"""
CREATE TABLE IF NOT EXISTS
`{{catalog}}`.`{{dst_db}}`.`{{dst_tbl}}`
USING iceberg
AS SELECT * FROM `{{src_db}}`.`{{src_tbl}}`
LIMIT 0
"""
else:
# Handle query with or without catalog name provided
if src_catalog:
sql_query_d = f"""
CREATE TABLE IF NOT EXISTS
`{{catalog}}`.`{{dst_db}}`.`{{dst_tbl}}`
USING iceberg
PARTITIONED BY {{dst_partitions}}
AS SELECT * FROM `{{src_catalog}}`.`{{src_db}}`.`{{src_tbl}}`
LIMIT 0
"""
else:
sql_query_d = f"""
CREATE TABLE IF NOT EXISTS
`{{catalog}}`.`{{dst_db}}`.`{{dst_tbl}}`
USING iceberg
PARTITIONED BY {{dst_partitions}}
AS SELECT * FROM `{{src_db}}`.`{{src_tbl}}`
LIMIT 0
"""
# Run the CTAS SQL query
spark_sql_query_d = spark.sql(sql_query_d)
except Exception as e:
print(e)
raise e
else:
print(f"Create Table as Select (CTAS) completed....")
# Function for performing a querying on a Table
def query_table_data(catalog, db, tbl):
"""
Check that we can access the Table data
:param:
"""
# Handle query with or without catalog name provided
if catalog:
sql_query_data = f"""SELECT *
FROM `{{catalog}}`.`{{db}}`.`{{tbl}}`
limit 10
"""
else:
sql_query_data = f"""SELECT *
FROM `{{db}}`.`{{tbl}}`
limit 10
"""
try:
# Run Spark SQL Query
spark_sql_query_data = spark.sql(sql_query_data)
except Exception as e:
print(e)
raise e
else:
return spark_sql_query_data
# Main workflow Function, calls other functions as needed
def initiate_workflow():
"""
Initiate Migration Workflow
"""
try:
# First let's query the source table
print(f"Let do a test query of the source table {{data_source_db}}.{{data_source_tbl}} to see if we can perform a successful query")
if data_source_type == 'Standard':
query_table_data(None, data_source_db, data_source_tbl)
elif data_source_type == 'Iceberg':
query_table_data(data_source_catalog, data_source_db, data_source_tbl)
print(f"Test query of the source table {{data_source_db}}.{{data_source_tbl}} is successful proceeding to main task")
# Choose the CTAS option to create new Amazon S3 Table Bucket destination NameSpace and Table
if data_migration_type == 'New-Migration':
print(f"We are performing a new migration, so will use CTAS to create a new table and load data")
if data_source_type == 'Iceberg':
print(f"Source Table type is Hive....")
ctas_action(data_source_catalog, data_destination_catalog, data_source_db, data_source_tbl, data_destination_s3tables_namespace,
data_destination_s3tables_tbl, data_destination_s3tables_partitions
)
# Now that we have successfully created the destination table, let's perform an INSERT INTO
insert_update_action(data_source_catalog, data_destination_catalog, data_source_db, data_source_tbl,
data_destination_s3tables_namespace, data_destination_s3tables_tbl)
elif data_source_type == 'Standard':
ctas_action(None, data_destination_catalog, data_source_db, data_source_tbl, data_destination_s3tables_namespace,
data_destination_s3tables_tbl, data_destination_s3tables_partitions
)
# Now that we have successfully created the destination table, let's perform an INSERT INTO
insert_update_action(None, data_destination_catalog, data_source_db, data_source_tbl,
data_destination_s3tables_namespace, data_destination_s3tables_tbl)
# Now we are done with CTAS and INSERT INTO, let's perform some verifications on the destination Table
# Let's query the destination table
print(f"Let do a test query of the destination table {{data_destination_s3tables_namespace}}.{{data_destination_s3tables_tbl}} to see if we can perform a successful query")
query_table_data(data_destination_catalog, data_destination_s3tables_namespace, data_destination_s3tables_tbl)
print(f"Test query of the destination table {{data_destination_s3tables_namespace}}.{{data_destination_s3tables_tbl}} is successful!! ")
""" Migration and verification was successful!"""
except Exception as e:
print(e)
sys.exit(1)
else:
# Finalize Job
print("Successful Job completion")
if __name__ == "__main__":
# Start the Main Task
initiate_workflow()
'''
# End F String and PySpark Blob
# Initiating Main Function
def lambda_handler(event, context):
logger.info(f'Event detail is: {event}')
# Start Cloudformation Invocation #
if event.get('RequestType') == 'Create':
# logger.info(event)
try:
logger.info("Stack event is Create or Update, Uploading PySpark to S3 Bucket...")
# Now upload the Script to the Solution Amazon S3 Bucket!.
stream_to_s3(my_bucket, my_asset1_key, my_blob)
responseData = {}
responseData['message'] = "Successful"
logger.info(f"Sending Invocation Response {responseData['message']} to Cloudformation Service")
cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData)
except Exception as e:
logger.error(e)
responseData = {}
responseData['message'] = str(e)
failure_reason = str(e)
logger.info(f"Sending Invocation Response {responseData['message']} to Cloudformation Service")
cfnresponse.send(event, context, cfnresponse.FAILED, responseData, reason=failure_reason)
else: