forked from atlanhq/presto-on-aws
-
Notifications
You must be signed in to change notification settings - Fork 0
/
presto.yaml
1354 lines (1268 loc) · 48.9 KB
/
presto.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: 'CloudFormation Template for OpenSource Presto'
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
-
Label:
default: "AWS Configuration"
Parameters:
- VPC
- Subnet
- KeyName
- SecurityGroups
-
Label:
default: "Presto Configuration"
Parameters:
- CoordinatorInstanceType
- WorkersInstanceType
- WorkersCount
- Ec2RootVolumeSize
- MaxWorkersCount
-
Label:
default: "Additional Parameters"
Parameters:
- Environment
Mappings:
RegionMap:
ap-south-1:
PRESTOIMAGE: ami-0bcffb0a9872eb14c
us-east-1:
PRESTOIMAGE: ami-04254dc35836a5c71
Parameters:
VPC:
Type: 'AWS::EC2::VPC::Id'
#aws-permission @cft ec2:DescribeVpcs
Description: VPC ID
AllowedPattern: ".+"
Subnet:
Type: 'AWS::EC2::Subnet::Id'
#aws-permission @cft ec2:DescribeSubnets
Description: Subnet to use for Presto nodes (must belong to the selected VPC)
AllowedPattern: ".+"
KeyName:
Description: EC2 Key Name
Type: AWS::EC2::KeyPair::KeyName
#aws-permission @cft ec2:DescribeKeyPairs
AllowedPattern: ".+"
SecurityGroups:
Type: 'List<AWS::EC2::SecurityGroup::Id>'
#aws-permission @cft ec2:DescribeSecurityGroups
Description: 'Security Groups for Presto nodes (e.g: allowing SSH access). Must select at least one.'
AllowedPattern: ".+"
CoordinatorInstanceType:
Type: String
Default: m5.large
Description: EC2 instance type of the coordinator
CoordinatorInstanceCount:
Type: String
Default: 1
Description: Number of Coordinator instances to deploy
WorkersInstanceType:
Type: String
Default: m5.large
Description: EC2 instance type of the workers
ElasticsearchHost:
Type: String
Default: dev-admin-search.atlan.com
ElasticsearchPort:
Type: "String"
Default: 443
AdditionalConfigsUri:
Type: "String"
Description: Additional Configuration zip file to use, provide an https s3 public url to fetch the zip file from.
WorkersCount:
Description: Number of dedicated Presto worker nodes (apart from coordinator) to instantiate.
Type: Number
Default: 1
MinValue: 1
MaxWorkersCount:
Description: Number of max dedicated Presto worker nodes.
Type: Number
Default: 5
MinValue: 1
Ec2RootVolumeSize:
Type: String
Default: 100
Description: EC2 root volume size
HiveIPAddress:
Type: String
Default: thrift://emr.dev.services:9083
Description: Hive IP Address
Environment:
Type: String
Description: Presto Launch Environment
AllowedValues:
- dev
- prod
Default: "dev"
PrestoVersion:
Type: String
Default: 330
Description: Presto Version which is being deployed
Resources:
PrestoSecurityGroup:
Type: "AWS::EC2::SecurityGroup"
#aws-permission @cft ec2:CreateSecurityGroup
#aws-permission @cft ec2:DeleteSecurityGroup
Properties:
GroupDescription: Presto nodes Security Group
VpcId: !Ref VPC
Tags:
- { Key: Name, Value: !Sub "${AWS::StackName}-presto-sg" }
- { Key: "presto:opensource:identification:role", Value: "presto:security-group" }
PrestoHttpsOutboundRule:
Type: AWS::EC2::SecurityGroupEgress
#aws-permission @cft ec2:AuthorizeSecurityGroupEgress
#aws-permission @cft ec2:RevokeSecurityGroupEgress
Properties:
IpProtocol: tcp
FromPort: '443'
ToPort: '443'
CidrIp: 0.0.0.0/0
GroupId: !GetAtt PrestoSecurityGroup.GroupId
PrestoOutboundRule:
Type: AWS::EC2::SecurityGroupEgress
#aws-permission @cft ec2:AuthorizeSecurityGroupEgress
#aws-permission @cft ec2:RevokeSecurityGroupEgress
Properties:
IpProtocol: tcp
FromPort: '8080'
ToPort: '8080'
DestinationSecurityGroupId: !GetAtt PrestoSecurityGroup.GroupId
GroupId: !GetAtt PrestoSecurityGroup.GroupId
PrestoInboundRule:
Type: AWS::EC2::SecurityGroupIngress
#aws-permission @cft ec2:AuthorizeSecurityGroupIngress
#aws-permission @cft ec2:RevokeSecurityGroupIngress
Properties:
IpProtocol: tcp
FromPort: '8080'
ToPort: '8080'
SourceSecurityGroupId: !GetAtt PrestoSecurityGroup.GroupId
GroupId: !GetAtt PrestoSecurityGroup.GroupId
PrestoClusterIAMRole:
Type: AWS::IAM::Role
#aws-permission @cft iam:CreateRole
#aws-permission @cft iam:DeleteRole
# Condition: CreateIamInstanceProfile
Properties:
RoleName: !Sub ${AWS::StackName}-presto-cluster-iam-role
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service: [ec2.amazonaws.com, apigateway.amazonaws.com]
Action: ['sts:AssumeRole']
Policies:
#aws-permission @cft iam:AttachRolePolicy
#aws-permission @cft iam:DeleteRolePolicy
#aws-permission @cft iam:DetachRolePolicy
#aws-permission @cft iam:PutRolePolicy
- PolicyName: !Sub ${AWS::StackName}-presto-cf-policy
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- "autoscaling:CompleteLifecycleAction"
- "autoscaling:RecordLifecycleActionHeartbeat"
- "autoscaling:DescribeAutoScalingGroups"
- "autoscaling:PutScalingPolicy"
- "autoscaling:DescribeAutoScalingInstances"
- "autoscaling:DescribeLaunchConfigurations"
- "autoscaling:DescribeScalingActivities"
- "autoscaling:UpdateAutoScalingGroup"
- "autoscaling:SetDesiredCapacity"
- "cloudformation:SignalResource"
- "ec2:DescribeInstances"
- "glue:BatchGetPartition"
- "glue:BatchCreatePartition"
- "glue:CreateDatabase"
- "glue:CreateTable"
- "glue:DeleteDatabase"
- "glue:DeletePartition"
- "glue:DeleteTable"
- "glue:GetDatabase"
- "glue:GetDatabases"
- "glue:GetPartition"
- "glue:GetPartitions"
- "glue:GetTable"
- "glue:GetTables"
- "glue:UpdateTable"
- "glue:UpdatePartition"
- "s3:GetObject"
- "s3:ListBucket"
- "s3:PutObject"
- "sqs:ChangeMessageVisibility"
- "sqs:DeleteMessage"
- "sqs:GetQueueUrl"
- "sqs:ReceiveMessage"
- "logs:CreateLogGroup"
- "logs:CreateLogStream"
- "logs:PutLogEvents"
- "logs:PutRetentionPolicy"
- "logs:DescribeLogGroups"
- "logs:DescribeLogStreams"
- "cloudwatch:PutMetricData"
- "ec2:CreateNetworkInterface"
- "ec2:DescribeNetworkInterfaces"
- "ec2:DeleteNetworkInterface"
- "ec2:AttachNetworkInterface"
- "ec2:DetachNetworkInterface"
- "ec2:DescribeNetworkInterfaceAttribute"
Resource:
- "*"
PrestoClusterInstanceProfile:
Type: AWS::IAM::InstanceProfile
#aws-permission @cft iam:CreateInstanceProfile
#aws-permission @cft iam:DeleteInstanceProfile
#aws-permission @cft iam:GetRole
#aws-permission @cft iam:AddRoleToInstanceProfile
#aws-permission @cft iam:RemoveRoleFromInstanceProfile
Properties:
Roles:
- Ref: PrestoClusterIAMRole
CoordinatorENI:
Type: 'AWS::EC2::NetworkInterface'
#aws-permission @cft ec2:CreateNetworkInterface
#aws-permission @cft ec2:DescribeNetworkInterfaces
#aws-permission @cft ec2:ModifyNetworkInterfaceAttribute
#aws-permission @cft ec2:DeleteNetworkInterface
Properties:
Description: !Sub "${AWS::StackName} coordinator ENI"
GroupSet: !Split
- ','
- !Join
- ','
- - !GetAtt PrestoSecurityGroup.GroupId
- !Join
- ','
- !Ref SecurityGroups
SubnetId: !Ref Subnet
Tags:
- { Key: Name, Value: !Sub "${AWS::StackName}-coordinator-ENI" }
- { Key: "presto:opensource:identification:role", Value: "presto:coordinator-eni" }
PrestoCoordinatorServerLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub /prestosql/presto/${AWS::StackName}/coordinators/server
RetentionInDays: 7
PrestoCoordinatorSyslogLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub /prestosql/presto/${AWS::StackName}/coordinators/syslog
RetentionInDays: 3
PrestoWorkerServerLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub /prestosql/presto/${AWS::StackName}/workers/server
RetentionInDays: 1
PrestoWorkerSyslogLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub /prestosql/presto/${AWS::StackName}/workers/syslog
RetentionInDays: 1
Coordinator:
Type: 'AWS::AutoScaling::LaunchConfiguration'
#aws-permission @cft autoscaling:CreateLaunchConfiguration
#aws-permission @cft autoscaling:DeleteLaunchConfiguration
#aws-permission @cft autoscaling:DescribeLaunchConfigurations
Properties:
InstanceType: !Ref CoordinatorInstanceType
ImageId: !FindInMap [RegionMap, !Ref "AWS::Region", PRESTOIMAGE]
BlockDeviceMappings:
- DeviceName: /dev/xvda
Ebs:
DeleteOnTermination: true
VolumeSize: !Ref Ec2RootVolumeSize
VolumeType: gp2
KeyName: !Ref KeyName
#aws-permission @cft iam:GetInstanceProfile
IamInstanceProfile: !Ref PrestoClusterInstanceProfile
SecurityGroups: !Split
- ','
- !Join
- ','
- - !GetAtt PrestoSecurityGroup.GroupId
- !Join
- ','
- !Ref SecurityGroups
UserData:
Fn::Base64:
!Sub |
#!/bin/bash
set -xtrace
sed -i -e "s/{{isCoordinator}}/true/g" /etc/presto/config.properties
sed -i -e "s#{{coordinatorDiscoveryUri}}#http://localhost:8080#g" /etc/presto/config.properties
echo "" >> /etc/presto/config.properties
echo discovery-server.enabled=true >> /etc/presto/config.properties
R=$(($(grep MemTotal /proc/meminfo | awk '{print $2}')/1048576))
X=$(($R*8/10))
sed -i -e "s/{{jvmMemory}}/$X/g" /etc/presto/jvm.config
sed -i -e "s/{{envName}}/${Environment}/g" /etc/presto/node.properties
sed -i -e "s/{{instanceId}}/$(curl http://169.254.169.254/latest/meta-data/instance-id/)/g" /etc/presto/node.properties
Z=$(($X*6/10))
echo "query.max-memory-per-node="$Z"GB" >> /etc/presto/config.properties
Y=$(($X*7/10))
echo "query.max-total-memory-per-node="$Y"GB" >> /etc/presto/config.properties
echo "query.max-memory=1PB" >> /etc/presto/config.properties
echo "query.low-memory-killer.policy=total-reservation-on-blocked-nodes" >> /etc/presto/config.properties
sudo tee /etc/awslogs/awslogs.conf > /dev/null <<EOT
[general]
state_file = /tmp/awslogs.state
[/var/log/prsto/server.log]
file = /var/log/presto/server.log
datetime_format = %b %d %H:%M:%S
initial_position = start_of_file
log_group_name = ${PrestoCoordinatorServerLogGroup}
log_stream_name = {instance_id}
[/var/log/messages]
datetime_format = %b %d %H:%M:%S
file = /var/log/messages
buffer_duration = 5000
initial_position = start_of_file
log_group_name = ${PrestoCoordinatorSyslogLogGroup}
log_stream_name = {instance_id}
EOT
sudo tee /etc/awslogs/awscli.conf > /dev/null <<EOT
[plugins]
cwlogs = cwlogs
[default]
region = ${AWS::Region}
EOT
sudo tee /etc/presto/catalog/hive.properties > /dev/null <<EOT
connector.name=hive-hadoop2
hive.metastore.uri=${HiveIPAddress}
EOT
sudo tee /etc/presto_cw_agent.conf > /dev/null <<EOT
PRESTO_STACK_NAME=${AWS::StackName}
EOT
wget -O /tmp/presto_config.zip ${AdditionalConfigsUri}
unzip /tmp/presto_config.zip -d /tmp/
cat /tmp/config/config.properties >> /etc/presto/config.properties
cat /tmp/config/catalog/hive.properties >> /etc/presto/catalog/hive.properties
cp /tmp/config/catalog/jmx.properties /etc/presto/catalog/jmx.properties
cp /tmp/config/catalog/tpch.properties /etc/presto/catalog/tpch.properties
cp /tmp/config/catalog/tpcds.properties /etc/presto/catalog/tpcds.properties
mkdir -p /usr/lib/presto/plugin/atlan-audit-logger-presto-experimental/
rm -rf /usr/lib/presto/plugin/atlan-audit-logger-presto-experimental/*
wget -O /usr/lib/presto/plugin/atlan-audit-logger-presto-experimental/QueryAuditEventListener-1.4-prestosql.jar https://github.com/atlanhq/presto-query-logger/releases/download/v1.3/presto-query-logger-1.3.jar
mkdir /usr/lib/presto/etc/
sudo tee /usr/lib/presto/etc/event-listener.properties > /dev/null <<EOT
event-listener.name=atlan-audit-logger
es-host=${ElasticsearchHost}
es-port=${ElasticsearchPort}
es-protocol=http
es-type=_doc
EOT
prestoVersion=$((${PrestoVersion}+0))
apiPrefix='v1/'
if (( $prestoVersion > 329 )); then
echo "Presto version greater than 329"
apiPrefix='ui/api/'
fi
cat <<EOF > /etc/presto_metrics/env.prometheus
PRESTO_HOST=localhost
PRESTO_PORT=8080
SERVICE_NAME=prometheus
STACK_NAME=${AWS::StackName}
CLOUDWATCH_NAMESPACE=presto
API_PREFIX=$apiPrefix
EOF
cat <<EOF > /etc/presto_metrics/env.cloudwatch
PRESTO_HOST=localhost
PRESTO_PORT=8080
SERVICE_NAME=cloudwatch
STACK_NAME=${AWS::StackName}
CLOUDWATCH_NAMESPACE=presto
CLOUDWATCH_REGION=${AWS::Region}
API_PREFIX=$apiPrefix
EOF
systemctl start awslogsd
service presto start
HTTP_URL="http://localhost:8080/v1/status"
CURL_CMD="curl -w httpcode=%{http_code}"
# -m, --max-time <seconds> FOR curl operation
CURL_MAX_CONNECTION_TIMEOUT="-m 5"
# perform curl operation
for i in {1..30}
do
sleep 5
CURL_RETURN_CODE=0
CURL_OUTPUT=`$CURL_CMD $CURL_MAX_CONNECTION_TIMEOUT $HTTP_URL 2> /dev/null` || CURL_RETURN_CODE=$?
if [ $CURL_RETURN_CODE -ne 0 ]; then
echo "Curl connection failed with return code - $CURL_RETURN_CODE"
else
echo "Success"
break
fi
done
if [ $CURL_RETURN_CODE -ne 0 ]; then
/opt/aws/bin/cfn-signal -s 'false' --stack ${AWS::StackName} --resource Coordinators --region ${AWS::Region}
else
systemctl start presto_metrics_prometheus.service
systemctl start presto_metrics_cloudwatch.service
/opt/aws/bin/cfn-signal -s 'true' --stack ${AWS::StackName} --resource Coordinators --region ${AWS::Region}
fi
Coordinators:
Type: 'AWS::AutoScaling::AutoScalingGroup'
#aws-permission @cft autoscaling:CreateAutoScalingGroup
#aws-permission @cft autoscaling:DeleteAutoScalingGroup
#aws-permission @cft autoscaling:DescribeAutoScalingGroups
#aws-permission @cft autoscaling:UpdateAutoScalingGroup
#aws-permission @cft autoscaling:DescribeScalingActivities
#aws-permission @cft autoscaling:DescribeLaunchConfigurations
#aws-permission @cft autoscaling:DescribeAutoScalingInstances
#aws-permission @cft ec2:CreateTags
#aws-permission @cft ec2:RunInstances
#aws-permission @cft ec2:TerminateInstances
#aws-permission @cft ec2:DescribeInstances
UpdatePolicy:
# Make updates to LaunchConfiguration cause rolling update of coordinators
AutoScalingReplacingUpdate:
WillReplace: true
CreationPolicy:
ResourceSignal:
Timeout: PT15M
Count: !Ref CoordinatorInstanceCount
Properties:
LaunchConfigurationName: !Ref Coordinator
VPCZoneIdentifier:
- !Ref Subnet
MinSize: !Ref CoordinatorInstanceCount
MaxSize: !Ref CoordinatorInstanceCount
DesiredCapacity: !Ref CoordinatorInstanceCount
Tags:
- { Key: Name, Value: !Sub "${AWS::StackName}-presto-coordinator", PropagateAtLaunch: true }
- { Key: "presto:opensource:identification:role", Value: "presto:coordinator", PropagateAtLaunch: true }
HealthCheckGracePeriod: 300
HealthCheckType: ELB
LoadBalancerNames: !Split
- ','
- !Join
- ','
- - !Ref PrestoCoordinatorsELB
Worker:
Type: 'AWS::AutoScaling::LaunchConfiguration'
#aws-permission @cft autoscaling:CreateLaunchConfiguration
#aws-permission @cft autoscaling:DeleteLaunchConfiguration
#aws-permission @cft autoscaling:DescribeLaunchConfigurations
#aws-permission @cft autoscaling:UpdateAutoScalingGroup
Properties:
InstanceType: !Ref WorkersInstanceType
ImageId: !FindInMap [RegionMap, !Ref "AWS::Region", PRESTOIMAGE]
BlockDeviceMappings:
- DeviceName: /dev/xvda
Ebs:
DeleteOnTermination: true
VolumeSize: !Ref Ec2RootVolumeSize
VolumeType: gp2
KeyName: !Ref KeyName
#aws-permission @cft iam:GetInstanceProfile
IamInstanceProfile: !Ref PrestoClusterInstanceProfile
SecurityGroups: !Split
- ','
- !Join
- ','
- - !GetAtt PrestoSecurityGroup.GroupId
- !Join
- ','
- !Ref SecurityGroups
# When worker has private IP only, following things are problematic:
# - S3 cannot be accessed (can be fixed with NAT box in VPC or "VPC endpoint for S3")
# - EC2 boot is very long, as it includes `yum upgrade` which retries timeouts (can
# be fixed with NAT box in VPC or "repo_upgrade: none" in cloud init)
#AssociatePublicIpAddress: false
UserData:
Fn::Base64:
!Sub |
#!/bin/bash
set -xtrace
sed -i -e "s/{{isCoordinator}}/false/g" /etc/presto/config.properties
sed -i -e "s#{{coordinatorDiscoveryUri}}#http://${CoordinatorENI.PrimaryPrivateIpAddress}:8080#g" /etc/presto/config.properties
R=$(($(grep MemTotal /proc/meminfo | awk '{print $2}')/1048576))
X=$(($R*8/10))
sed -i -e "s/{{jvmMemory}}/$X/g" /etc/presto/jvm.config
sed -i -e "s/{{envName}}/${Environment}/g" /etc/presto/node.properties
sed -i -e "s/{{instanceId}}/$(curl http://169.254.169.254/latest/meta-data/instance-id/)/g" /etc/presto/node.properties
echo "" >> /etc/presto/config.properties
Z=$(($X*6/10))
echo "query.max-memory-per-node="$Z"GB" >> /etc/presto/config.properties
Y=$(($X*7/10))
echo "query.max-total-memory-per-node="$Y"GB" >> /etc/presto/config.properties
echo "query.low-memory-killer.policy=total-reservation-on-blocked-nodes" >> /etc/presto/config.properties
sudo tee /etc/awslogs/awslogs.conf > /dev/null <<EOT
[general]
state_file = /tmp/awslogs.state
[/var/log/prsto/server.log]
file = /var/log/presto/server.log
datetime_format = %b %d %H:%M:%S
initial_position = start_of_file
log_group_name = ${PrestoWorkerServerLogGroup}
log_stream_name = {instance_id}
[/var/log/messages]
datetime_format = %b %d %H:%M:%S
file = /var/log/messages
buffer_duration = 5000
initial_position = start_of_file
log_group_name = ${PrestoWorkerSyslogLogGroup}
log_stream_name = {instance_id}
EOT
sudo tee /etc/awslogs/awscli.conf > /dev/null <<EOT
[plugins]
cwlogs = cwlogs
[default]
region = ${AWS::Region}
EOT
sudo tee /etc/presto/catalog/hive.properties > /dev/null <<EOT
connector.name=hive-hadoop2
hive.metastore.uri=${HiveIPAddress}
EOT
wget -O /tmp/presto_config.zip ${AdditionalConfigsUri}
unzip /tmp/presto_config.zip -d /tmp/
cat /tmp/config/config.properties >> /etc/presto/config.properties
cat /tmp/config/catalog/hive.properties >> /etc/presto/catalog/hive.properties
cp /tmp/config/catalog/jmx.properties /etc/presto/catalog/jmx.properties
cp /tmp/config/catalog/tpch.properties /etc/presto/catalog/tpch.properties
cp /tmp/config/catalog/tpcds.properties /etc/presto/catalog/tpcds.properties
mkdir /usr/lib/presto/plugin/atlan-audit-logger-presto-experimental/
mkdir /usr/lib/presto/etc/
rm -rf /usr/lib/presto/plugin/atlan-audit-logger-presto-experimental/*
wget -O /usr/lib/presto/plugin/atlan-audit-logger-presto-experimental/QueryAuditEventListener-1.4-prestosql.jar https://athena-cloudformation-templates.s3.ap-south-1.amazonaws.com/unilever/config/QueryAuditEventListener-1.4-prestosql-jar-with-dependencies.jar
sudo tee /usr/lib/presto/etc/event-listener.properties > /dev/null <<EOT
event-listener.name=atlan-audit-logger
es-host=${ElasticsearchHost}
es-port=${ElasticsearchPort}
es-protocol=http
es-type=_doc
EOT
prestoVersion=$((${PrestoVersion}+0))
apiPrefix='v1/'
if (( $prestoVersion > 329 )); then
echo "Presto version greater than 329"
apiPrefix='ui/api/'
fi
cat <<EOF > /etc/presto_metrics/env.prometheus
PRESTO_HOST=localhost
PRESTO_PORT=8080
SERVICE_NAME=prometheus
STACK_NAME=${AWS::StackName}
CLOUDWATCH_NAMESPACE=presto
API_PREFIX=$apiPrefix
EOF
cat <<EOF > /etc/presto_metrics/env.cloudwatch
PRESTO_HOST=localhost
PRESTO_PORT=8080
SERVICE_NAME=cloudwatch
STACK_NAME=${AWS::StackName}
CLOUDWATCH_NAMESPACE=presto
API_PREFIX=$apiPrefix
EOF
systemctl start awslogsd
service presto start
HTTP_URL="http://localhost:8080/v1/status"
CURL_CMD="curl -w httpcode=%{http_code}"
# -m, --max-time <seconds> FOR curl operation
CURL_MAX_CONNECTION_TIMEOUT="-m 5"
# perform curl operation
for i in {1..30}
do
sleep 5
CURL_RETURN_CODE=0
CURL_OUTPUT=`$CURL_CMD $CURL_MAX_CONNECTION_TIMEOUT $HTTP_URL 2> /dev/null` || CURL_RETURN_CODE=$?
if [ $CURL_RETURN_CODE -ne 0 ]; then
echo "Curl connection failed with return code - $CURL_RETURN_CODE"
else
echo "Success"
break
fi
done
if [ $CURL_RETURN_CODE -ne 0 ]; then
/opt/aws/bin/cfn-signal -s 'false' --stack ${AWS::StackName} --resource Workers --region ${AWS::Region}
else
systemctl start presto_metrics_prometheus.service
systemctl start presto_metrics_cloudwatch.service
/opt/aws/bin/cfn-signal -s 'true' --stack ${AWS::StackName} --resource Workers --region ${AWS::Region}
fi
Workers:
Type: 'AWS::AutoScaling::AutoScalingGroup'
#aws-permission @cft autoscaling:CreateAutoScalingGroup
#aws-permission @cft autoscaling:DeleteAutoScalingGroup
#aws-permission @cft autoscaling:DescribeAutoScalingGroups
#aws-permission @cft autoscaling:UpdateAutoScalingGroup
#aws-permission @cft autoscaling:DescribeScalingActivities
#aws-permission @cft autoscaling:DescribeLaunchConfigurations
#aws-permission @cft autoscaling:DescribeAutoScalingInstances
#aws-permission @cft ec2:CreateTags
#aws-permission @cft ec2:RunInstances
#aws-permission @cft ec2:TerminateInstances
#aws-permission @cft ec2:DescribeInstances
UpdatePolicy:
# Make updates to LaunchConfiguration cause rolling update of workers
AutoScalingReplacingUpdate:
WillReplace: true
CreationPolicy:
ResourceSignal:
Timeout: PT15M
Count: !Ref WorkersCount
Properties:
LaunchConfigurationName: !Ref Worker
MetricsCollection:
- Granularity: "1Minute"
VPCZoneIdentifier:
- !Ref Subnet
MinSize: !Ref WorkersCount
MaxSize: !Ref MaxWorkersCount
DesiredCapacity: !Ref WorkersCount
Tags:
- { Key: Name, Value: !Sub "${AWS::StackName}-presto-worker", PropagateAtLaunch: true }
- { Key: "presto:opensource:identification:role", Value: "presto:worker", PropagateAtLaunch: true }
HealthCheckGracePeriod: 180
HealthCheckType: ELB
LoadBalancerNames: !Split
- ','
- !Join
- ','
- - !Ref PrestoWorkersELB
WorkersScaleUpPolicy:
Type: AWS::AutoScaling::ScalingPolicy
Properties:
AdjustmentType: ChangeInCapacity
AutoScalingGroupName:
Ref: Workers
Cooldown: '60'
ScalingAdjustment: '1'
WorkersScaleDownPolicy:
Type: AWS::AutoScaling::ScalingPolicy
Properties:
AdjustmentType: ChangeInCapacity
AutoScalingGroupName:
Ref: Workers
Cooldown: '60'
ScalingAdjustment: "-1"
WorkersUserCPUAlarmHigh:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmDescription: Scale-up if CPU > 70% for 1 minutes
MetricName: MeanWorkerUserCPUUtilisation
Namespace: presto
Statistic: Average
Period: '120'
EvaluationPeriods: '1'
Threshold: '0.7'
AlarmActions:
- Ref: WorkersScaleUpPolicy
Dimensions:
- Name: prestoStackName
Value:
Ref: "AWS::StackName"
ComparisonOperator: GreaterThanThreshold
WorkersUserCPUAlarmLow:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmDescription: Scale-down if CPU < 50% for 5 minutes
MetricName: MeanWorkerUserCPUUtilisation
Namespace: presto
Statistic: Average
Period: '300'
EvaluationPeriods: '1'
Threshold: '0.5'
AlarmActions:
- Ref: WorkersScaleDownPolicy
Dimensions:
- Name: prestoStackName
Value:
Ref: "AWS::StackName"
ComparisonOperator: LessThanThreshold
WorkersSystemCPUAlarmHigh:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmDescription: Scale-up if CPU > 70% for 1 minutes
MetricName: MeanWorkerSystemCPUUtilisation
Namespace: presto
Statistic: Average
Period: '120'
EvaluationPeriods: '1'
Threshold: '0.7'
AlarmActions:
- Ref: WorkersScaleUpPolicy
Dimensions:
- Name: prestoStackName
Value:
Ref: "AWS::StackName"
ComparisonOperator: GreaterThanThreshold
WorkersSystemCPUAlarmLow:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmDescription: Scale-down if CPU < 50% for 5 minutes
MetricName: MeanWorkerSystemCPUUtilisation
Namespace: presto
Statistic: Average
Period: '300'
EvaluationPeriods: '1'
Threshold: '0.5'
AlarmActions:
- Ref: WorkersScaleDownPolicy
Dimensions:
- Name: prestoStackName
Value:
Ref: "AWS::StackName"
ComparisonOperator: LessThanThreshold
GracefulNodeShutdownQueueIAMRole:
Type: AWS::IAM::Role
#aws-permission @cft iam:CreateRole
#aws-permission @cft iam:DeleteRole
#Condition: CreateIamInstanceProfile
Properties:
RoleName: !Sub ${AWS::StackName}-graceful-shutdown-iam-role
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service:
- ec2.amazonaws.com
- lambda.amazonaws.com
Action: ['sts:AssumeRole']
Policies:
#aws-permission @cft iam:AttachRolePolicy
#aws-permission @cft iam:DeleteRolePolicy
#aws-permission @cft iam:DetachRolePolicy
#aws-permission @cft iam:PutRolePolicy
- PolicyName: !Sub ${AWS::StackName}-graceful-shutdown-iam-role
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- "ec2:DescribeInstances"
- "sqs:ReceiveMessage"
- "sqs:SendMessage"
- "sqs:DeleteMessage"
- "sqs:GetQueueAttributes"
- "sqs:GetQueueUrl"
- "logs:PutLogEvents"
- "logs:CreateLogStream"
- "logs:CreateLogGroup"
- "ec2:CreateNetworkInterface"
- "ec2:DescribeNetworkInterfaces"
- "ec2:DeleteNetworkInterface"
- "ec2:AttachNetworkInterfaces"
Resource:
- "*"
AutoScalingTerminationWaitLambdaIAMRole:
Type: AWS::IAM::Role
#aws-permission @cft iam:CreateRole
#aws-permission @cft iam:DeleteRole
#Condition: CreateIamInstanceProfile
Properties:
RoleName: !Sub ${AWS::StackName}-asg-terminate-lambda-iam-role
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service:
- ec2.amazonaws.com
- lambda.amazonaws.com
Action: ['sts:AssumeRole']
Policies:
#aws-permission @cft iam:AttachRolePolicy
#aws-permission @cft iam:DeleteRolePolicy
#aws-permission @cft iam:DetachRolePolicy
#aws-permission @cft iam:PutRolePolicy
- PolicyName: !Sub ${AWS::StackName}-asg-terminate-lambda-iam-role
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- "autoscaling:CompleteLifecycleAction"
- "sqs:ReceiveMessage"
- "sqs:SendMessage"
- "sqs:GetQueueUrl"
- "sqs:GetQueueAttributes"
- "sqs:DeleteMessage"
- "logs:PutLogEvents"
- "logs:CreateLogStream"
- "logs:CreateLogGroup"
- "ec2:CreateNetworkInterface"
- "ec2:DescribeNetworkInterfaces"
- "ec2:DeleteNetworkInterface"
- "ec2:AttachNetworkInterfaces"
- "ec2:Describe*"
Resource:
- "*"
GracefulNodeShutdownQueue:
Type: 'AWS::SQS::Queue'
#aws-permission @cft sqs:CreateQueue
#aws-permission @cft sqs:DeleteQueue
#aws-permission @cft sqs:GetQueueAttributes
#aws-permission @cft sqs:TagQueue
Properties:
# This is required so that threads that handle those messages will not try to process the same message over and over again
# The value is higher than the usual graceful shutdown, so that in most cases there will not be a need to request
# more time. Otherwise if the handling thread is reaching 250s it will tell SQS to keep his message private for longer.
# See AWS docs on VisibilityTimeout for more details.
VisibilityTimeout: 250
AutoScalingTerminationWaitQueue:
Type: 'AWS::SQS::Queue'
Properties:
VisibilityTimeout: 250
AutoScalingNotificationIAMRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- autoscaling.amazonaws.com
- ec2.amazonaws.com
Action:
- 'sts:AssumeRole'
Path: /
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AutoScalingNotificationAccessRole
- arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess
GracefulPrestoNodeShutdownHook:
Type: "AWS::AutoScaling::LifecycleHook"
#aws-permission @cft autoscaling:PutLifecycleHook
#aws-permission @cft autoscaling:DeleteLifecycleHook
Properties:
AutoScalingGroupName: !Ref Workers
LifecycleTransition: 'autoscaling:EC2_INSTANCE_TERMINATING'
NotificationTargetARN: !GetAtt GracefulNodeShutdownQueue.Arn
RoleARN: !GetAtt AutoScalingNotificationIAMRole.Arn
HeartbeatTimeout: 3600
DefaultResult: CONTINUE
GracefulNodeShutdownLambda:
Type: "AWS::Lambda::Function"
Properties:
Code:
ZipFile: |
import os
import json
import boto3
from botocore.vendored import requests
def lambda_handler(event, context):
# TODO implement
print(event)
event_body = json.loads(event['Records'][0]["body"])
if event_body["LifecycleTransition"] != "autoscaling:EC2_INSTANCE_TERMINATING":
print("Not a terminating condition return")
return
ec2_instance_id = event_body["EC2InstanceId"]
instance_id = ec2_instance_id
ec2 = boto3.resource('ec2')
ec2_instance = ec2.Instance(instance_id)
ip = ec2_instance.private_ip_address
for i in range(3):
try:
url = 'http://{}:8080/v1/info/state'.format(ip)
payload = "\"SHUTTING_DOWN\""
headers = {
'Content-Type': "application/json",
'cache-control': "no-cache"
}
response = requests.request("PUT", url, data=payload, headers=headers)
print(response.text)
except Exception as e:
pass
print(ip)
queue_url = os.getenv('QUEUE_URL')
print(queue_url)
sqs = boto3.client('sqs')
response = sqs.send_message(
QueueUrl=queue_url,
MessageBody=json.dumps(event_body)
)
print(response)
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}
Environment:
Variables:
QUEUE_URL: !Ref AutoScalingTerminationWaitQueue
COORDINATOR_IP: !GetAtt CoordinatorENI.PrimaryPrivateIpAddress
Role: !GetAtt GracefulNodeShutdownQueueIAMRole.Arn
Timeout: 10
Handler: index.lambda_handler
Runtime: python3.6
VpcConfig:
SubnetIds:
- !Ref Subnet
SecurityGroupIds: !Split
- ','
- !Join
- ','
- - !GetAtt PrestoSecurityGroup.GroupId
- !Join
- ','
- !Ref SecurityGroups
GracefulNodeShutdownLambdaEventSourceMapping:
Type: AWS::Lambda::EventSourceMapping
Properties:
BatchSize: 1
EventSourceArn: !GetAtt GracefulNodeShutdownQueue.Arn
FunctionName: !GetAtt GracefulNodeShutdownLambda.Arn
DependsOn:
- GracefulNodeShutdownLambda
- GracefulNodeShutdownQueue
AutoScalingTerminationWaitLambda:
Type: "AWS::Lambda::Function"
Properties:
Code:
ZipFile: |
import json
import boto3
import os
from botocore.vendored import requests
def lambda_handler(event, context):
# TODO implement
def enqueue_message(event_body):
queue_url = os.getenv('QUEUE_URL')
print(queue_url)
sqs = boto3.client('sqs')
response = sqs.send_message(