-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathjolly-roger.yaml
1044 lines (981 loc) · 38.9 KB
/
jolly-roger.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
# This YAML file can be used as a CloudFormation Stack to spin up the
# jolly-roger environment. This file is loaded directly into CloudFormation,
# which means that some features of YAML (e.g. references) are unavailable.
#
# The jolly-roger environment consists of:
#
# - A VPC with a public subnet
#
# - A system for fetching secrets using AWS Systems Manager Parameter Store
# which encrypts secrets using KMS.
#
# - An auto-scaling group (ASG) with instances that automatically launch the
# jolly-roger application.
#
# - The application instances run several docker services:
#
# - An haproxy instance for port 443, listening for incoming TCP connections
# (HTTPS, or potentially STUN, but unwrapped by NLB), separating STUN,
# HTTP/2, and HTTP traffic and forwarding as appropriate to coturn or nginx
#
# - An nginx instance, listening for HTTP connections on port 8443 and HTTP/2
# connections on port 8444 (nginx doesn't support using the same port for
# plaintext HTTP/1 and HTTP/2) and forwarding to the application, and
# listening on port 80 to redirect to HTTPS
#
# - A coturn server for TURN proxying if needed for audio conferencing
#
# - The actual Meteor application
#
# - Watchtower, which periodically pulls image updates
#
# - A Network Load Balancer (NLB) in front of the ASG, forwarding ports 80 and
# 443 to ports 80 and 443 on application servers. NLB is responsible for
# terminating TLS, but otherwise forwards network traffic unmodified.
#
# It's possible this could be used to run multiple parallel copies of the
# jolly-roger website, though that's not very likely in practice.
#
# To spin up an independent copy of jolly-roger, you'll _definitely_ need to do
# the following (and probably more I've forgotten):
#
# - Set up a certificate in AWS Certificate Manager for the domain. The ARN will
# be configured as the CertificateArn paramater.
#
# - Provide the MongoDB URL. The free account from mongodb.com (for instance)
# should be sufficient. You can configure a user using the "AWS IAM"
# authentication method, the type "IAM Role", and the ARN
# "arn:aws:iam::<AWS Account ID>:role/JollyRogerAppInstanceRole"; then you can
# specify authMechanism=MONGODB-AWS in the URL and do not need to provide a
# username/password. You will need to configure the user with the "Atlas
# admin" built-in role, and to enable connections from 0.0.0.0/0 (all IPs)
# since the EC2 instance IPs aren't static.
#
# You can either set the MongoUrl and MongoOplogUrl parameters here, or set
# them using `aws ssm put-parameter --type "SecureString" --name "mongo"
# --value "<path>"` and `aws ssm put-parameter --type "SecureString" --name
# "mongo.oplog" --value "<path>"` (e.g. if you're using regular username/
# password credentials as part of the URLs).
#
# - Signup for a Mailgun account (or any mail provider that supports SMTP
# submission), and add an SMTP URL with the SMTP credentials from your mailgun
# account. The URL format should be something like:
#
# smtp://postmaster%40yourdomain.com:[email protected]:587
#
# Store that using `aws ssm put-parameter --type "SecureString" --name
# "mailgun" --value "<path>"`.
AWSTemplateFormatVersion: "2010-09-09"
Description: jolly-roger
Parameters:
CertificateArn:
Description: ARN of the certificate to use
Type: String
AppName:
Description: The user-facing name of the app
Type: String
Default: Jolly Roger
AppUrl:
Description: The domain name of application
Type: String
Default: future.deathandmayhem.com
AppDomain:
Description: The zone under which to create DNS records
Type: AWS::Route53::HostedZone::Id
AppInstanceType:
Description: Instance type to run for app server
Type: String
Default: t3a.micro
AppMinSize:
Description: Minimum number of instances for app server ASG
Type: Number
Default: 1
AppMaxSize:
Description: Maximum number of instances for app server ASG
Type: Number
Default: 2
AppDesiredCapacity:
Description: Desired number of instances for app server ASG
Type: Number
Default: 1
DockerPackage:
Description: Docker package containing the app to deploy
Type: String
Default: "ghcr.io/deathandmayhem/jolly-roger"
PapertrailHost:
Description: Log host for Papertrail
Type: String
Default: ""
NoEcho: true
TurnSecret:
Description: TURN REST API secret
Type: String
AllowedPattern: "^[A-Za-z0-9]+$"
NoEcho: true
MongoUrl:
Description: MONGO_URL to use with Meteor. Can leave unset and use "mongo" key in SSM if using username/password authentication.
Type: String
Default: ""
MongoOplogUrl:
Description: MONGO_OPLOG_URL to use with Meteor. Can leave unset and use "mongo.oplog" key in SSM if using username/password authentication.
Type: String
Default: ""
CloudWatchMode:
Description: Mode to use with CloudWatch. "None" disables CloudWatch. "Minimal" only captures memory and swap metrics to keep costs down (note that total CPU is a built-in metric). "Detailed" also captures disk, network, and detailed CPU metrics.
Type: String
Default: "Detailed"
AllowedValues: ["Detailed", "Minimal", "None"]
SshUsers:
Description: Comma-separated list of SSH users, each of the form <username>=<ssh_import_id>
Type: String
Default: "evan=gh:ebroder,zarvox=gh:zarvox"
ServingMode:
Description: |
In "NLB" mode, bring up a load balancer and point the domain to it, allowing scaling to
multiple EC2 jobs. TLS termination is handled by the NLB using the certificate referenced
in CertificateArn. In "SingleInstance" mode, the domain is pointed directly at a single
EC2 instance. The TLS certificate will be automatically managed via Let's Encrypt - be sure
to accept their terms of service. In "None" mode, all serving is disabled. Use this to shut
down the app and save on costs while keeping persistent resources like the S3 bucket alive
and making it simpler to enable serving in the future.
Type: String
Default: "NLB"
AllowedValues: ["NLB", "SingleInstance", "None"]
CertNotificationEmail:
Description: Email to use for certificate abuse and renewal notifications when using Let's Encrypt via the SingleInstance serving mode. Leave blank to disable notifications.
Type: String
Default: ""
Conditions:
HavePapertrail: !Not [!Equals [!Ref PapertrailHost, ""]]
HaveCloudWatch: !Not [!Equals [!Ref CloudWatchMode, "None"]]
HaveCloudWatchDetailed: !Equals [!Ref CloudWatchMode, "Detailed"]
HaveServing: !Not [!Equals [!Ref ServingMode, "None"]]
HaveLoadBalancing: !Equals [!Ref ServingMode, "NLB"]
HaveSingleInstance: !Equals [!Ref ServingMode, "SingleInstance"]
Resources:
LambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: [lambda.amazonaws.com]
Action: ["sts:AssumeRole"]
Policies:
- PolicyName: root
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: "arn:aws:logs:*:*:*"
- Effect: Allow
Action:
- ec2:AssociateAddress
- ec2:ReleaseAddress
Resource: "arn:aws:ec2:*:*:*"
SshUsersParsingFunction:
Type: AWS::Lambda::Function
Properties:
Description: Generate the SSH users docker config from the raw input parameter
Runtime: nodejs18.x
Handler: "index.main"
Role: !GetAtt LambdaExecutionRole.Arn
Environment:
Variables:
sshUsers:
Ref: SshUsers
Code:
ZipFile: |
const response = require('cfn-response');
exports.main = function (event, context) {
const sshUsers = process.env.sshUsers.split(',');
var output = 'users:\n'
sshUsers.forEach((sshUser) => {
const parts = sshUser.split('=');
output += ` - name: ${parts[0]}\n`
output += ` shell: /bin/bash\n`
output += ` ssh_import_id: ${parts[1]}\n`
output += ` sudo: ALL=(ALL) NOPASSWD:ALL\n`
});
response.send(event, context, response.SUCCESS, { Output: output });
};
SshUsersParsing:
Type: Custom::SshUsersParsing
Properties:
ServiceToken: !GetAtt SshUsersParsingFunction.Arn
Suite: jammy
Region: !Ref "AWS::Region"
InstanceType: ebs-ssd
Architecture: amd64
VirtualizationType: hvm
VPC:
Type: AWS::EC2::VPC
Condition: HaveServing
Properties:
CidrBlock: 10.32.0.0/16
EnableDnsHostnames: true
PublicSubnetRouteTable:
Type: AWS::EC2::RouteTable
Condition: HaveServing
Properties:
VpcId: !Ref VPC
InternetGateway:
Type: AWS::EC2::InternetGateway
Condition: HaveServing
InternetGatewayAttachment:
Type: AWS::EC2::VPCGatewayAttachment
Condition: HaveServing
Properties:
VpcId: !Ref VPC
InternetGatewayId: !Ref InternetGateway
PublicRouteToInternet:
Type: AWS::EC2::Route
Condition: HaveServing
Properties:
DestinationCidrBlock: 0.0.0.0/0
GatewayId: !Ref InternetGateway
RouteTableId: !Ref PublicSubnetRouteTable
DependsOn: InternetGatewayAttachment
PublicSubnet1:
Type: AWS::EC2::Subnet
Condition: HaveServing
Properties:
AvailabilityZone: !Select [0, !GetAZs ""]
CidrBlock: 10.32.0.0/24
MapPublicIpOnLaunch: true
VpcId: !Ref VPC
PublicSubnet1RouteTableAssoc:
Type: AWS::EC2::SubnetRouteTableAssociation
Condition: HaveServing
Properties:
RouteTableId: !Ref PublicSubnetRouteTable
SubnetId: !Ref PublicSubnet1
PublicSubnet2:
Type: AWS::EC2::Subnet
Condition: HaveServing
Properties:
AvailabilityZone: !Select [1, !GetAZs ""]
CidrBlock: 10.32.1.0/24
MapPublicIpOnLaunch: true
VpcId: !Ref VPC
PublicSubnet2RouteTableAssoc:
Type: AWS::EC2::SubnetRouteTableAssociation
Condition: HaveServing
Properties:
RouteTableId: !Ref PublicSubnetRouteTable
SubnetId: !Ref PublicSubnet2
ImageUploadBucket:
Type: AWS::S3::Bucket
Properties:
PublicAccessBlockConfiguration:
BlockPublicAcls: false
BlockPublicPolicy: false
IgnorePublicAcls: false
RestrictPublicBuckets: false
ImageUploadBucketPolicy:
Type: AWS::S3::BucketPolicy
Properties:
Bucket: !Ref ImageUploadBucket
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal: "*"
Action: ["s3:GetObject"]
Resource: !Sub "arn:aws:s3:::${ImageUploadBucket}/*"
AppInstanceRole:
Type: AWS::IAM::Role
Properties:
RoleName: "JollyRogerAppInstanceRole"
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: [ec2.amazonaws.com]
Action: ["sts:AssumeRole"]
ManagedPolicyArns:
- arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy
Policies:
- PolicyName: ssm-download
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- ssm:DescribeParameters
- ssm:GetParameters
- ssm:GetParameter
Resource: !Sub "arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/*"
- PolicyName: s3-uploads
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- s3:ListAllMyBuckets
Resource: "*"
- Effect: Allow
Action:
- s3:ListBucket
- s3:GetBucketLocation
Resource: !Sub "arn:aws:s3:::${ImageUploadBucket}"
- Effect: Allow
Action:
- s3:PutObject
Resource: !Sub "arn:aws:s3:::${ImageUploadBucket}/*"
- PolicyName: dns-updates
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- route53:ListHostedZones
- route53:GetChange
Resource: "*"
- Effect: Allow
Action:
- route53:ChangeResourceRecordSets
Resource: !Sub "arn:aws:route53:::hostedzone/${AppDomain}"
AppInstanceProfile:
Type: AWS::IAM::InstanceProfile
Properties:
Path: /
Roles:
- !Ref AppInstanceRole
AppSecurityGroup:
Type: AWS::EC2::SecurityGroup
Condition: HaveServing
Properties:
GroupDescription: Security group for app server instances
SecurityGroupEgress:
- CidrIp: 0.0.0.0/0
IpProtocol: -1
FromPort: -1
ToPort: -1
SecurityGroupIngress:
- CidrIp: 0.0.0.0/0
IpProtocol: tcp
FromPort: 22
ToPort: 22
- CidrIp: 0.0.0.0/0
IpProtocol: tcp
FromPort: 80
ToPort: 80
- CidrIp: 0.0.0.0/0
IpProtocol: tcp
FromPort: 443
ToPort: 443
- Description: Mediasoup RTC ports
CidrIp: 0.0.0.0/0
IpProtocol: udp
FromPort: 50000
ToPort: 65535
- Description: Mediasoup RTC ports
CidrIp: 0.0.0.0/0
IpProtocol: tcp
FromPort: 50000
ToPort: 65535
- Description: TURN relay ports
CidrIp: 0.0.0.0/0
IpProtocol: udp
FromPort: 40000
ToPort: 49999
- Description: ICMP echo request
CidrIp: 0.0.0.0/0
IpProtocol: icmp
FromPort: 8
ToPort: -1
- Description: ICMP echo reply
CidrIp: 0.0.0.0/0
IpProtocol: icmp
FromPort: 0
ToPort: -1
- Description: ICMP frag needed
CidrIp: 0.0.0.0/0
IpProtocol: icmp
FromPort: 3
ToPort: 4
VpcId: { Ref: VPC }
AppNlb:
Type: AWS::ElasticLoadBalancingV2::LoadBalancer
Condition: HaveLoadBalancing
Properties:
Type: network
Scheme: internet-facing
Subnets:
- !Ref PublicSubnet1
- !Ref PublicSubnet2
AppNlbTargetHTTP:
Type: AWS::ElasticLoadBalancingV2::TargetGroup
Condition: HaveLoadBalancing
Properties:
HealthCheckProtocol: HTTP
HealthCheckPort: 443
HealthCheckPath: /healthcheck
HealthCheckIntervalSeconds: 5
HealthCheckTimeoutSeconds: 4
HealthyThresholdCount: 2
UnhealthyThresholdCount: 2
Protocol: TCP
Port: 80
VpcId: !Ref VPC
TargetGroupAttributes:
- Key: preserve_client_ip.enabled
Value: true
AppNlbTargetHTTPS:
Type: AWS::ElasticLoadBalancingV2::TargetGroup
Condition: HaveLoadBalancing
Properties:
HealthCheckProtocol: HTTP
HealthCheckPort: 443
HealthCheckPath: /healthcheck
HealthCheckIntervalSeconds: 5
HealthCheckTimeoutSeconds: 4
HealthyThresholdCount: 2
UnhealthyThresholdCount: 2
Protocol: TCP
Port: 443
VpcId: !Ref VPC
TargetGroupAttributes:
- Key: preserve_client_ip.enabled
Value: true
AppNlbListenerHTTP:
Type: AWS::ElasticLoadBalancingV2::Listener
Condition: HaveLoadBalancing
Properties:
LoadBalancerArn: !Ref AppNlb
Protocol: TCP
Port: 80
DefaultActions:
- Type: forward
TargetGroupArn: !Ref AppNlbTargetHTTP
AppNlbListenerHTTPS:
Type: AWS::ElasticLoadBalancingV2::Listener
Condition: HaveLoadBalancing
Properties:
LoadBalancerArn: !Ref AppNlb
Protocol: TLS
Port: 443
Certificates:
- { CertificateArn: !Ref CertificateArn }
AlpnPolicy: [HTTP2Preferred]
DefaultActions:
- Type: forward
TargetGroupArn: !Ref AppNlbTargetHTTPS
AppLaunchTemplate:
Type: AWS::EC2::LaunchTemplate
Condition: HaveServing
Properties:
LaunchTemplateData:
IamInstanceProfile:
Arn: !GetAtt AppInstanceProfile.Arn
ImageId: resolve:ssm:/aws/service/canonical/ubuntu/server/22.04/stable/current/amd64/hvm/ebs-gp2/ami-id
BlockDeviceMappings:
- DeviceName: /dev/sda1
Ebs:
VolumeType: gp3
VolumeSize: 12
- DeviceName: /dev/sdb
VirtualName: ephemeral0
- DeviceName: /dev/sdc
VirtualName: ephemeral1
InstanceType: !Ref AppInstanceType
SecurityGroupIds:
- !Ref AppSecurityGroup
# We're generating a YAML file inside a YAML file. Yes, this is
# gross, but it seems to be the best anyone has come up with
# (especially since we need variable interpolation)
UserData:
Fn::Base64: !Sub
- |
#cloud-config
package_upgrade: true
apt:
sources:
docker.list:
source: "deb [arch=amd64] https://download.docker.com/linux/ubuntu $RELEASE stable"
keyid: "8D81803C0EBFCD88"
${SshUsersConfig}
swap:
filename: "/swapfile"
size: 2147483648 # 2GB
packages:
- awscli
- docker-ce
- docker-ce-cli
- containerd.io
- htop
- moreutils
- python3-dev
- python3-pip
- certbot
- python3-certbot-dns-route53
- socat
${PapertrailRsyslogConfig}
write_files:
- path: /etc/cron.hourly/docker-cleanup
content: |
#!/bin/sh
docker volume ls -qf dangling=true | chronic xargs -r docker volume rm
permissions: "0755"
- path: /etc/docker/daemon.json
content: |
{
"log-driver": "json-file",
"log-opts": {
"max-size": "100m"
}
}
- path: /usr/local/bin/renew-certificate
content: |
#!/bin/bash
set -e
# Renew the certificate and update haproxy's offline copy.
if [ -n "${CertNotificationEmail}" ]; then
email_flag="-m ${CertNotificationEmail}"
else
email_flag="--register-unsafely-without-email"
fi
certbot -v certonly --dns-route53 -d ${AppUrl} --non-interactive --agree-tos $email_flag
mkdir -p /etc/haproxy/certs/
cat /etc/letsencrypt/live/${AppUrl}/fullchain.pem /etc/letsencrypt/live/${AppUrl}/privkey.pem | tee /etc/haproxy/certs/cert.pem > /dev/null
# If haproxy is running, perform a live certificate update.
if [ -f /var/run/haproxy/stats.sock ]; then
echo -e "set ssl cert /usr/local/etc/haproxy/certs/cert.pem <<\n$(cat /etc/haproxy/certs/cert.pem)\n" | socat stdio /var/run/haproxy/stats.sock
echo -e "commit ssl cert /usr/local/etc/haproxy/certs/cert.pem" | socat stdio /var/run/haproxy/stats.sock
fi
permissions: "0755"
- path: /usr/share/nginx/html/502.html
content: |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>${AppName} :: Temporarily Down</title>
<style type="text/css">
/* Standard font */
@import url("https://fonts.googleapis.com/css2?family=Source+Sans+Pro:ital,wght@0,400;0,700;1,400;1,700&display=swap");
body {
font-family: "Platform Emoji", "Source Sans Pro", "Helvetica Neue", "Helvetica", "Arial", sans-serif, "Noto Color Emoji", "Apple Color Emoji", "Segoe UI Emoji";
font-size: 16px;
line-height: 1.5;
max-width: 800px;
margin: 0 auto;
padding: 1em;
}
h1 {
font-size: 2.5em;
font-weight: 500;
margin: 0;
}
p {
margin-top: 0;
}
.warning {
color: #842029;
background-color: #f8d7da;
border: 1px solid #f5c2c7;
margin: 1em 0;
padding: 0.75em 1.25em;
border-radius: 0.375rem;
}
.warning p {
margin: 0;
}
.hidden {
display: none;
}
@keyframes spinner {
to {transform: rotate(360deg);}
}
.spinner:before {
content: '';
box-sizing: border-box;
position: relative;
display: inline-block;
top: 50%;
left: 50%;
width: 20px;
height: 20px;
margin-top: -10px;
margin-left: -10px;
border-radius: 50%;
border: 2px solid #ccc;
border-top-color: #000;
animation: spinner .6s linear infinite;
}
</style>
</head>
<body>
<h1>Temporarily Down</h1>
<div class="warning hidden">
<p>
<strong>Warning:</strong> The ${AppName} server is taking longer than expected to come back up.
Please contact the ${AppName} team if this problem persists.
</p>
</div>
<p>
The ${AppName} server is temporarily down. Usually this happens when a new
version is being deployed. This page will automatically refresh once the site
is back up.
</p>
<p>
<span class="spinner"></span>
</p>
<script>
// Attempt to refresh every 5 seconds. After 1 minute, display a warning that
// it's taking longer than expected.
const deadline = Date.now() + 60 * 1000;
let timeout = null;
const tick = async () => {
if (Date.now() > deadline) {
document.querySelector(".warning").classList.remove("hidden");
}
try {
const response = await fetch(window.location.href, { method: "HEAD" })
if (response.ok) {
clearTimeout(timeout);
window.location.reload();
}
} catch (e) {
console.log(e);
}
timeout = setTimeout(tick, 4500 + Math.random() * 1000);
};
tick();
</script>
</body>
</html>
- path: /etc/haproxy/haproxy.cfg
content: |
global
# Enable runtime API for live certificate updates
stats socket /var/run/haproxy/stats.sock mode 600 level admin
maxconn 50000
log stdout local0
defaults
mode tcp
log global
option tcplog
option logasap
timeout connect 5s
timeout client 50s
timeout server 50s
frontend inbound
bind :443 ${SingleInstanceCertReference}
tcp-request inspect-delay 5s
# don't pick backend until we've seen enough to identify
# both STUN and HTTP/2 (STUN headers are only 20 bytes, so
# we can't check the full standard HTTP/2 prefix)
acl seen_headers req.len gt 20
tcp-request content accept if seen_headers
# In STUN, the first two bits are always 0 (to convert to
# an int, we need to go through a hex string)
acl is_turn_prefix req.payload(0,1),hex,hex2i,and(196),not
# ...and the 4th-7th byte have the magic cookie
acl is_turn_magic_cookie req.payload(4,4) -m bin 2112a442
# Meanwhile HTTP/2 always starts with "PRI * HTTP/2.0\r\n\r\nSM"
acl is_http2_prefix req.payload(0,20) -m bin 505249202a20485454502f322e300d0a0d0a534d
use_backend nginx-http2 if is_http2_prefix
use_backend turn if is_turn_prefix is_turn_magic_cookie
default_backend nginx
backend turn
server turn localhost:3478
backend nginx
server nginx localhost:8443 send-proxy
mode http
backend nginx-http2
server nginx-http2 localhost:8444 send-proxy
- path: /etc/nginx/conf.d/default.conf
content: |
# If we receive Upgrade, set Connection to "upgrade"; otherwise, delete any
# Connection header that may have been passed to this server
map $http_upgrade $proxy_connection {
default upgrade;
'' close;
}
gzip_types text/plain text/css application/javascript application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
log_format access '[$time_iso8601] $remote_addr - "$request" $status $body_bytes_sent $request_time $upstream_cache_status "$http_referer" "$http_user_agent"';
access_log /var/log/nginx/access.log access;
# HTTP 1.1 support
proxy_http_version 1.1;
proxy_buffering on;
proxy_set_header Host $http_host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $proxy_connection;
proxy_set_header X-Forwarded-For $proxy_protocol_addr;
# Mitigate httpoxy attack
proxy_set_header Proxy "";
proxy_cache_path /var/cache/nginx/cache levels=1:2 keys_zone=assets:10m;
proxy_cache assets;
set_real_ip_from 127.0.0.1;
real_ip_header proxy_protocol;
upstream jolly-roger {
server 127.0.0.1:3000;
}
server {
server_name ${AppUrl};
listen 8443 proxy_protocol default_server;
listen 8444 proxy_protocol http2 default_server;
add_header Strict-Transport-Security "max-age=31536000";
gzip on;
gzip_comp_level 9;
gzip_proxied any;
location /healthcheck {
return 200 "OK\n";
}
location / {
proxy_pass http://jolly-roger;
}
error_page 502 /502.html;
location = /502.html {
root /usr/share/nginx/html;
internal;
}
}
server {
server_name ${AppUrl};
listen 80 default_server;
return 301 https://$host$request_uri;
}
- path: /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json
content: |
{
"metrics": {
"append_dimensions": {
"AutoScalingGroupName": "${!aws:AutoScalingGroupName}",
"ImageId": "${!aws:ImageId}",
"InstanceId": "${!aws:InstanceId}",
"InstanceType": "${!aws:InstanceType}"
},
"metrics_collected": {
${CloudWatchMetrics}
}
}
}
runcmd:
- set -eux
# Whatever happens, let cloudformation know
- pip3 install https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-py3-latest.tar.gz
- cleanup() { ret=$?; set +e; cfn-signal -e $ret -r "runcmds complete" --stack=${AWS::StackName} --region=${AWS::Region} --resource=AppAsg; exit $ret; }
- trap cleanup EXIT
# Uninstall Amazon SSM manager and snapd - we don't use them, and they eat memory (and cause swap-thrashing)
- snap remove amazon-ssm-agent
- sudo apt-get remove -y snapd
# Disable certbot's built-in scheduled task - we use our own so we can also refresh haproxy.
- sudo systemctl stop certbot.timer
- sudo systemctl disable certbot.timer
- export AWS_DEFAULT_REGION=${AWS::Region}
${CloudWatchAgentConfig}
${PapertrailDockerConfig}
${SingleInstanceCertConfig}
- docker run --name coturn -d --restart=unless-stopped --network=host -e DETECT_EXTERNAL_IP=yes coturn/coturn -v --min-port=40000 --max-port=49999 --log-file=stdout --realm=${AppUrl} --use-auth-secret --static-auth-secret=${TurnSecret}
- docker run --name jolly-roger -d --network=host --restart=unless-stopped -e AWS_REGION=$AWS_DEFAULT_REGION -e AWS_DEFAULT_REGION=$AWS_DEFAULT_REGION -e PORT=3000 -e ROOT_URL=https://${AppUrl} -e TURN_SERVER=turns:${AppUrl}:443?transport=tcp -e TURN_SECRET=${TurnSecret} -e MONGO_URL="${MongoUrl}" -e MONGO_OPLOG_URL="${MongoOplogUrl}" ${DockerPackage}
- docker run --name nginx -d --network=host --restart=unless-stopped -v /etc/nginx/conf.d/default.conf:/etc/nginx/conf.d/default.conf -v /usr/share/nginx/html/502.html:/usr/share/nginx/html/502.html nginx
- docker run --name watchtower -d --restart=unless-stopped -v /var/run/docker.sock:/var/run/docker.sock containrrr/watchtower --interval 30 --cleanup
- docker run --name haproxy -d --restart=unless-stopped --user root --network=host -v /var/run/haproxy:/var/run/haproxy -v /etc/haproxy:/usr/local/etc/haproxy:ro haproxy
- PapertrailRsyslogConfig: !If
- HavePapertrail
- !Sub |
rsyslog:
remotes:
papertrail: ${PapertrailHost}
- ""
PapertrailDockerConfig: !If
- HavePapertrail
- !Sub '- docker run --name logspout -d --restart=unless-stopped -v /var/run/docker.sock:/tmp/docker.sock -e "SYSLOG_HOSTNAME=$(hostname){{.Container.Name}}" gliderlabs/logspout:master syslog://${PapertrailHost}'
- ""
CloudWatchAgentConfig: !If
- HaveCloudWatch
- |2
# Observability
- curl -O https://s3.amazonaws.com/amazoncloudwatch-agent/ubuntu/amd64/latest/amazon-cloudwatch-agent.deb
- dpkg -i ./amazon-cloudwatch-agent.deb
- rm amazon-cloudwatch-agent.deb
- sudo systemctl start amazon-cloudwatch-agent
- ""
CloudWatchMetrics: !If
- HaveCloudWatchDetailed
- '"mem": {
"measurement": ["mem_used_percent"]
},
"swap": {
"measurement": ["swap_used_percent"]
},
"cpu": {
"measurement": [
"cpu_usage_idle",
"cpu_usage_iowait",
"cpu_usage_user",
"cpu_usage_system"
]
},
"diskio": {
"measurement": [
"io_time",
"write_bytes",
"read_bytes",
"writes",
"reads"
]
},
"netstat": {
"measurement": [
"tcp_established",
"tcp_time_wait"
]
}'
- '"mem": {
"measurement": ["mem_used_percent"]
},
"swap": {
"measurement": ["swap_used_percent"]
}'
SshUsersConfig: !GetAtt SshUsersParsing.Output
SingleInstanceCertConfig: !If
- HaveLoadBalancing
- ""
- "- sudo ln -s /usr/local/bin/renew-certificate /etc/cron.daily/ && /usr/local/bin/renew-certificate"
SingleInstanceCertReference: !If
- HaveLoadBalancing
- ""
- ssl crt /usr/local/etc/haproxy/certs/
AppInstancePublicIp:
Type: AWS::EC2::EIP
Condition: HaveSingleInstance
Properties:
Domain: "vpc"
DependsOn:
- InternetGatewayAttachment
AssociateSingleInstanceIpFunction:
Type: AWS::Lambda::Function
Condition: HaveServing
Properties:
Description: Associate the elastic IP with the single EC2 instance whenever it launches successfully
Runtime: nodejs18.x
Handler: "index.main"
Role: !GetAtt LambdaExecutionRole.Arn
Code:
ZipFile: !Sub
- |
const { EC2Client, AssociateAddressCommand } = require('@aws-sdk/client-ec2');
exports.main = async function (event) {
const client = new EC2Client({ region: event.region });
const params = {
AllocationId: '${AllocationId}',
InstanceId: event.detail['EC2InstanceId'],
};
const command = new AssociateAddressCommand(params);
try {
await client.send(command);
return {
statusCode: 200,
body: JSON.stringify('SUCCESS'),
};
} catch (err) {
console.log(err, err.stack);
return {
statusCode: 500,
body: JSON.stringify('ERROR'),
};
};
};
- AllocationId: !If
- HaveLoadBalancing
- ""
- !GetAtt AppInstancePublicIp.AllocationId
AssociateSingleInstanceIpRule:
Type: AWS::Events::Rule
Condition: HaveServing
Properties:
EventPattern:
source:
- aws.autoscaling
detail-type:
- EC2 Instance Launch Successful
detail:
AutoScalingGroupName:
- "JollyRogerAsg"
State: !If
- HaveLoadBalancing
- DISABLED
- ENABLED
Targets:
- Id: AssociateSingleInstanceIpHookTarget
Arn: !GetAtt AssociateSingleInstanceIpFunction.Arn
AssociateSingleInstanceIpFunctionPermission:
Type: AWS::Lambda::Permission
Condition: HaveServing
Properties:
FunctionName: !GetAtt AssociateSingleInstanceIpFunction.Arn
Action: lambda:InvokeFunction
Principal: events.amazonaws.com
SourceArn: !GetAtt AssociateSingleInstanceIpRule.Arn
AppAsg:
Type: AWS::AutoScaling::AutoScalingGroup
Condition: HaveServing
Properties:
AutoScalingGroupName: "JollyRogerAsg"
HealthCheckType: !If
- HaveLoadBalancing
- ELB
- EC2
HealthCheckGracePeriod: 1800
LaunchTemplate:
LaunchTemplateId: !Ref AppLaunchTemplate
Version: !GetAtt AppLaunchTemplate.LatestVersionNumber
VPCZoneIdentifier:
- !Ref PublicSubnet1
- !Ref PublicSubnet2
MaxSize: !Ref AppMaxSize
MinSize: !Ref AppMinSize