This repository has been archived by the owner on Jan 8, 2024. It is now read-only.
/
platform.go
3393 lines (2867 loc) · 104 KB
/
platform.go
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
package ecs
import (
"context"
"encoding/json"
"fmt"
"sort"
"strconv"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatchlogs"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ecs"
"github.com/aws/aws-sdk-go/service/elbv2"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/route53"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/hashicorp/go-hclog"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/hashicorp/waypoint-plugin-sdk/component"
"github.com/hashicorp/waypoint-plugin-sdk/docs"
"github.com/hashicorp/waypoint-plugin-sdk/framework/resource"
sdk "github.com/hashicorp/waypoint-plugin-sdk/proto/gen"
"github.com/hashicorp/waypoint-plugin-sdk/terminal"
"github.com/hashicorp/waypoint/builtin/aws/utils"
"github.com/hashicorp/waypoint/builtin/docker"
)
const (
executionRolePolicyArn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
awsCreateRetries = 30
awsCreateRetryIntervalSeconds = 2
// Five minutes of retrying for destroy - destroys are slower than creates in aws.
awsDestroyRetries = 60
awsDestroyRetryIntervalSeconds = 5
defaultServicePort = 3000
)
type Platform struct {
config Config
}
// Config implements Configurable
func (p *Platform) Config() (interface{}, error) {
return &p.config, nil
}
// ConfigSet is called after a configuration has been decoded
// we can use this to validate the config
func (p *Platform) ConfigSet(config interface{}) error {
c, ok := config.(*Config)
if !ok {
// this should never happen
return status.Errorf(codes.FailedPrecondition, "invalid configuration, expected *ecs.Config, got %T", config)
}
if c.ALB != nil {
alb := c.ALB
err := utils.Error(validation.ValidateStruct(alb,
// ZoneId and FQDN are both used to create a route53 record that points to an ALB.
// While we could still create this, if a user is managing their own ALB out of band,
// they probably also want to manage the route53 record themselves
// too.
validation.Field(&alb.ZoneId,
validation.Empty.When(alb.LoadBalancerArn != ""),
validation.Required.When(alb.FQDN != ""),
),
validation.Field(&alb.FQDN,
validation.Empty.When(alb.LoadBalancerArn != ""),
validation.Required.When(alb.ZoneId != "").Error("fqdn only valid with zone_id"),
),
validation.Field(&alb.InternalScheme,
validation.Nil.When(alb.LoadBalancerArn != "").Error("internal cannot be used with load_balancer_arn"),
),
validation.Field(&alb.LoadBalancerArn,
validation.Empty.When(
alb.ZoneId != "" ||
alb.FQDN != "" ||
len(alb.SecurityGroupIDs) >= 1).Error("load_balancer_arn can not be used with other options"),
),
validation.Field(&alb.SecurityGroupIDs),
))
if err != nil {
return err
}
}
err := utils.Error(validation.ValidateStruct(c,
validation.Field(&c.Memory, validation.Required, validation.Min(4)),
validation.Field(&c.MemoryReservation, validation.Min(4), validation.Max(c.Memory)),
))
if err != nil {
return err
}
if c.Architecture != "" {
c.Architecture = strings.ToUpper(c.Architecture)
cpuArchitectures := make([]interface{}, len(ecs.CPUArchitecture_Values()))
for i, ca := range ecs.CPUArchitecture_Values() {
cpuArchitectures[i] = ca
}
err := utils.Error(validation.ValidateStruct(c,
validation.Field(&c.Architecture,
validation.In(cpuArchitectures...).Error("unsupported CPU architecture"),
),
))
if err != nil {
return err
}
}
for _, cc := range c.ContainersConfig {
err := utils.Error(validation.ValidateStruct(cc,
validation.Field(&cc.Memory, validation.Required, validation.Min(4)),
validation.Field(&cc.MemoryReservation, validation.Min(4), validation.Max(cc.Memory)),
))
if err != nil {
return err
}
}
if c.HealthCheck != nil {
if c.HealthCheck.Timeout >= c.HealthCheck.Interval {
return status.Errorf(codes.FailedPrecondition, "the health check "+
"timeout must be less than the interval")
}
}
return nil
}
// DeployFunc implements component.Platform
func (p *Platform) DeployFunc() interface{} {
return p.Deploy
}
// DestroyFunc implements component.Destroyer
func (p *Platform) DestroyFunc() interface{} {
return p.Destroy
}
// ValidateAuthFunc implements component.Authenticator
func (p *Platform) ValidateAuthFunc() interface{} {
return p.ValidateAuth
}
// DestroyWorkspaceFunc implements component.WorkspaceDestroyer
func (p *Platform) DestroyWorkspaceFunc() interface{} {
return p.DestroyWorkspace
}
// AuthFunc implements component.Authenticator
func (p *Platform) AuthFunc() interface{} {
return p.Auth
}
func (p *Platform) Auth() error {
return nil
}
func (p *Platform) ValidateAuth() error {
return nil
}
// StatusFunc implements component.Status
func (p *Platform) StatusFunc() interface{} {
return p.Status
}
// DefaultReleaserFunc implements component.PlatformReleaser
func (p *Platform) DefaultReleaserFunc() interface{} {
return func() *Releaser { return &Releaser{p: p} }
}
func (p *Platform) resourceManager(log hclog.Logger, dcr *component.DeclaredResourcesResp, dtr *component.DestroyedResourcesResp) *resource.Manager {
return resource.NewManager(
resource.WithLogger(log.Named("resource_manager")),
resource.WithValueProvider(p.getSession),
resource.WithDeclaredResourcesResp(dcr),
resource.WithDestroyedResourcesResp(dtr),
resource.WithResource(resource.NewResource(
resource.WithName("cluster"),
resource.WithPlatform(platformName),
resource.WithState(&Resource_Cluster{}),
resource.WithCreate(p.resourceClusterCreate),
// TODO: implement destroy when we have better support for globally-scoped resources
resource.WithStatus(p.resourceClusterStatus),
resource.WithCategoryDisplayHint(sdk.ResourceCategoryDisplayHint_OTHER),
)),
resource.WithResource(resource.NewResource(
resource.WithName("execution role"),
resource.WithType("IAM role"),
resource.WithPlatform(platformName),
resource.WithState(&Resource_ExecutionRole{}),
resource.WithCreate(p.resourceExecutionRoleCreate),
// TODO: implement destroy when we have better support for app-scoped resources
// TODO: implement status when we have a plan to not hit rate limits
resource.WithCategoryDisplayHint(sdk.ResourceCategoryDisplayHint_POLICY),
)),
resource.WithResource(resource.NewResource(
resource.WithName("task role"),
resource.WithType("IAM role"),
resource.WithPlatform(platformName),
resource.WithState(&Resource_TaskRole{}),
resource.WithCreate(p.resourceTaskRoleCreate),
// TODO: implement destroy when we have better support for app-scoped resources
// TODO: implement status when we have a plan to not hit rate limits
resource.WithCategoryDisplayHint(sdk.ResourceCategoryDisplayHint_POLICY),
)),
resource.WithResource(resource.NewResource(
resource.WithName("internal security groups"),
resource.WithPlatform(platformName),
resource.WithType("security groups"),
resource.WithState(&Resource_InternalSecurityGroups{}),
resource.WithCreate(p.resourceInternalSecurityGroupsCreate),
// NOTE(izaak/nic): these are destroyed by resourceSecurityGroupsDestroy, registered under external security groups
// TODO: implement status when we have a plan to not hit rate limits
resource.WithCategoryDisplayHint(sdk.ResourceCategoryDisplayHint_POLICY),
)),
resource.WithResource(resource.NewResource(
resource.WithName("external security groups"),
resource.WithPlatform(platformName),
resource.WithType("security groups"),
resource.WithState(&Resource_ExternalSecurityGroups{}),
resource.WithCreate(p.resourceExternalSecurityGroupsCreate),
resource.WithDestroy(p.resourceSecurityGroupsDestroy),
// TODO: implement status when we have a plan to not hit rate limits
resource.WithCategoryDisplayHint(sdk.ResourceCategoryDisplayHint_POLICY),
)),
resource.WithResource(resource.NewResource(
resource.WithName("log group"),
resource.WithPlatform(platformName),
resource.WithState(&Resource_LogGroup{}),
resource.WithCreate(p.resourceLogGroupCreate),
// TODO: implement destroy when we have better support for waypoint global resources
// TODO: implement status when we have a plan to not hit rate limits
resource.WithCategoryDisplayHint(sdk.ResourceCategoryDisplayHint_OTHER),
)),
resource.WithResource(resource.NewResource(
resource.WithName("service subnets"),
resource.WithType("subnets"),
resource.WithPlatform(platformName),
resource.WithState(&Resource_ServiceSubnets{}),
resource.WithCreate(p.resourceServiceSubnetsDiscover),
// We never create subnets, and therefore should never destroy them
// TODO: implement status when we have a plan to not hit rate limits
resource.WithCategoryDisplayHint(sdk.ResourceCategoryDisplayHint_ROUTER),
)),
resource.WithResource(resource.NewResource(
resource.WithName("alb subnets"),
resource.WithType("subnets"),
resource.WithPlatform(platformName),
resource.WithState(&Resource_AlbSubnets{}),
resource.WithCreate(p.resourceAlbSubnetsDiscover),
// We never create subnets, and therefore should never destroy them
// TODO: implement status when we have a plan to not hit rate limits
resource.WithCategoryDisplayHint(sdk.ResourceCategoryDisplayHint_ROUTER),
)),
resource.WithResource(resource.NewResource(
resource.WithName("target group"),
resource.WithPlatform(platformName),
resource.WithState(&Resource_TargetGroup{}),
resource.WithCreate(p.resourceTargetGroupCreate),
resource.WithDestroy(p.resourceTargetGroupDestroy),
// TODO: implement status when we have a plan to not hit rate limits
resource.WithCategoryDisplayHint(sdk.ResourceCategoryDisplayHint_OTHER),
)),
resource.WithResource(resource.NewResource(
resource.WithName("application load balancer"),
resource.WithPlatform(platformName),
resource.WithState(&Resource_Alb{}),
resource.WithCreate(p.resourceAlbCreate),
resource.WithDestroy(p.resourceAlbDestroy),
// TODO: implement status when we have a plan to not hit rate limits
resource.WithCategoryDisplayHint(sdk.ResourceCategoryDisplayHint_ROUTER),
)),
resource.WithResource(resource.NewResource(
resource.WithName("alb listener"),
resource.WithPlatform(platformName),
resource.WithState(&Resource_Alb_Listener{}),
resource.WithCreate(p.resourceAlbListenerCreate),
resource.WithDestroy(p.resourceAlbListenerDestroy),
// TODO: implement status when we have a plan to not hit rate limits
resource.WithCategoryDisplayHint(sdk.ResourceCategoryDisplayHint_ROUTER),
)),
resource.WithResource(resource.NewResource(
resource.WithName("route53 record"),
resource.WithPlatform(platformName),
resource.WithState(&Resource_Route53Record{}),
resource.WithCreate(p.resourceRoute53RecordCreate),
// TODO: implement destroy when we have better support for app-scoped resources
// TODO: implement status when we have a plan to not hit rate limits
resource.WithCategoryDisplayHint(sdk.ResourceCategoryDisplayHint_ROUTER),
)),
resource.WithResource(resource.NewResource(
resource.WithName("task definition"),
resource.WithPlatform(platformName),
resource.WithState(&Resource_TaskDefinition{}),
resource.WithCreate(p.resourceTaskDefinitionCreate),
resource.WithDestroy(p.resourceTaskDefinitionDestroy),
// TODO: implement status when we have a plan to not hit rate limits
resource.WithCategoryDisplayHint(sdk.ResourceCategoryDisplayHint_INSTANCE_MANAGER),
)),
resource.WithResource(resource.NewResource(
resource.WithName("service"),
resource.WithPlatform(platformName),
resource.WithState(&Resource_Service{}),
resource.WithCreate(p.resourceServiceCreate),
resource.WithDestroy(p.resourceServiceDestroy),
resource.WithStatus(p.resourceServiceStatus),
resource.WithCategoryDisplayHint(sdk.ResourceCategoryDisplayHint_INSTANCE_MANAGER),
)),
)
}
// Below are custom types for various parameters used throughout resource creation.
// They exist as custom types so that argmapper can recognize and wire them
// into the appropriate resource lifecycle functions.
// DeploymentId is a unique ID to be consistently used throughout our deployment
type DeploymentId string
// WorkspaceDestroy marks that we're destroying the entire workspace (not just the deployment), and
// we should destroy global resources too
type WorkspaceDestroy bool
// ExternalIngressPort is the port that the ALB will listen for traffic on
type ExternalIngressPort int64
func (p *Platform) Deploy(
ctx context.Context,
log hclog.Logger,
src *component.Source,
img *docker.Image,
deployConfig *component.DeploymentConfig,
ui terminal.UI,
dcr *component.DeclaredResourcesResp,
) (*Deployment, error) {
var result Deployment
// We'll update the user in real time
sg := ui.StepGroup()
defer sg.Wait()
s := sg.Add("Initializing deployment...")
defer s.Abort()
// Generate a common deployment ID to use in the resources we create.
// TODO: should include the sequence ID
ulid, err := component.Id()
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to generate a ULID: %s", err)
}
deploymentId := DeploymentId(fmt.Sprintf("%s-%s", src.App, ulid))
// Set default port - it's used for multiple resources
if p.config.ServicePort != 0 {
log.Debug("Using configured service port", "port number", p.config.ServicePort)
} else {
log.Debug("Using the default service port", "port number", defaultServicePort)
p.config.ServicePort = int64(defaultServicePort)
}
// Set ALB ingress port - used for multiple resources
var externalIngressPort ExternalIngressPort
if p.config.ALB != nil && p.config.ALB.IngressPort != 0 {
log.Debug("Using configured ingress port", "port number", p.config.ServicePort)
externalIngressPort = ExternalIngressPort(p.config.ALB.IngressPort)
} else if p.config.ALB != nil && p.config.ALB.CertificateId != "" {
log.Debug("ALB config defined and cert configured, using ingress port 443")
externalIngressPort = ExternalIngressPort(443)
} else {
log.Debug("Defaulting external ingress port to 80")
externalIngressPort = ExternalIngressPort(80)
}
// Create our resource manager and create
rm := p.resourceManager(log, dcr, nil)
if err := rm.CreateAll(
ctx, log, sg, ui, deploymentId, externalIngressPort,
src, img, deployConfig, &result,
); err != nil {
return nil, status.Errorf(status.Convert(err).Code(), "failed to create deployment resources: %s", err)
}
// Store our resource state
result.ResourceState = rm.State()
// Get other state required for older versions to destroy this deployment
srState := rm.Resource("service").State().(*Resource_Service)
result.ServiceArn = srState.Arn
tgState := rm.Resource("target group").State().(*Resource_TargetGroup)
result.TargetGroupArn = tgState.Arn
albState := rm.Resource("application load balancer").State().(*Resource_Alb)
result.LoadBalancerArn = albState.Arn
listenerState := rm.Resource("alb listener").State().(*Resource_Alb_Listener)
result.ListenerArn = listenerState.Arn
cState := rm.Resource("cluster").State().(*Resource_Cluster)
result.Cluster = cState.Name
tdState := rm.Resource("task definition").State().(*Resource_TaskDefinition)
result.TaskArn = tdState.Arn
s.Update("Deployment resources created")
s.Done()
return &result, nil
}
func (p *Platform) Status(
ctx context.Context,
log hclog.Logger,
deployment *Deployment,
ui terminal.UI,
) (*sdk.StatusReport, error) {
sg := ui.StepGroup()
defer sg.Wait()
s := sg.Add("Gathering health report for ecs deployment...")
defer s.Abort()
rm := p.resourceManager(log, nil, nil)
// If we don't have resource state, this state is from an older version
// and we need to manually recreate it.
if deployment.ResourceState == nil {
if err := p.loadResourceManagerState(ctx, rm, deployment, log, sg); err != nil {
return nil, status.Errorf(codes.Internal, "failed recovering old state into resource manager: %s", err)
}
} else {
// Load our set state
if err := rm.LoadState(deployment.ResourceState); err != nil {
return nil, status.Errorf(codes.Internal, "failed loading state into resource manager: %s", err)
}
}
result, err := rm.StatusReport(ctx, log, sg)
if err != nil {
return nil, status.Errorf(status.Convert(err).Code(), "resource manager failed to generate a status report: %s", err)
}
s.Update("Finished building report for ecs deployment")
s.Done()
// NOTE(briancain): Replace ui.Status with StepGroups once this bug
// has been fixed: https://github.com/hashicorp/waypoint/issues/1536
st := ui.Status()
defer st.Close()
st.Update("Determining overall health for ecs deployment...")
if result.Health == sdk.StatusReport_READY {
st.Step(terminal.StatusOK, result.HealthMessage)
} else {
if result.Health == sdk.StatusReport_PARTIAL {
st.Step(terminal.StatusWarn, result.HealthMessage)
} else {
st.Step(terminal.StatusError, result.HealthMessage)
}
// Extra advisory wording to let user know that the deployment could be still starting up
// if the report was generated immediately after it was deployed or released.
st.Step(terminal.StatusWarn, mixedHealthWarn)
}
return result, nil
}
func (p *Platform) Destroy(
ctx context.Context,
log hclog.Logger,
deployment *Deployment,
ui terminal.UI,
dcr *component.DeclaredResourcesResp,
dtr *component.DestroyedResourcesResp,
) error {
sg := ui.StepGroup()
defer sg.Wait()
s := sg.Add("Destroying ecs deployment...")
defer s.Abort()
rm := p.resourceManager(log, dcr, dtr)
// If we don't have resource state, this state is from an older version
// and we need to manually recreate it.
if deployment.ResourceState == nil {
if err := p.loadResourceManagerState(ctx, rm, deployment, log, sg); err != nil {
return status.Errorf(codes.Internal, "failed recovering old state into resource manager: %s", err)
}
} else {
// Load our set state
if err := rm.LoadState(deployment.ResourceState); err != nil {
return status.Errorf(codes.Internal, "failed loading state into resource manager: %s", err)
}
}
// Destroy app-scoped resources
// Note: This calls the destroy func for all resources, but resource destroy funcs will use the WorkspaceDestroy
// param to only actually destroy if they are deployment scoped.
err := rm.DestroyAll(ctx, log, sg, ui, WorkspaceDestroy(false))
if err != nil {
return status.Errorf(status.Convert(err).Code(), "failed to destroy all resources for deployment: %s", err)
}
s.Update("Finished destroying ECS deployment")
s.Done()
return nil
}
func (p *Platform) DestroyWorkspace(
ctx context.Context,
log hclog.Logger,
deployment *Deployment,
app *component.Source,
ui terminal.UI,
) error {
sg := ui.StepGroup()
defer sg.Wait()
s := sg.Add("Destroying ecs workspace...")
defer s.Abort()
rm := p.resourceManager(log, nil, nil)
// If we don't have resource state, this state is from an older version
// and we need to manually recreate it.
if deployment.ResourceState == nil {
if err := p.loadResourceManagerState(ctx, rm, deployment, log, sg); err != nil {
return status.Errorf(codes.Internal, "failed recovering old state into resource manager: %s", err)
}
} else {
// Load our set state
if err := rm.LoadState(deployment.ResourceState); err != nil {
return status.Errorf(codes.Internal, "failed loading state into resource manager: %s", err)
}
}
// Destroy
// Note: This calls the destroy func for all resources, but resource destroy funcs will use the WorkspaceDestroy
// param to only actually destroy if they are workspace scoped.
err := rm.DestroyAll(ctx, log, sg, ui, WorkspaceDestroy(true))
if err != nil {
return status.Errorf(status.Convert(err).Code(), "failed to destroy all resources for workspace: %s", err)
}
s.Update("Finished destroying ECS deployment")
s.Done()
return nil
}
func (p *Platform) resourceClusterCreate(
ctx context.Context,
sg terminal.StepGroup,
log hclog.Logger,
sess *session.Session,
state *Resource_Cluster,
) error {
s := sg.Add("Initiating cluster creation...")
defer s.Abort()
cluster := p.config.Cluster
if cluster == "" {
cluster = "waypoint"
}
state.Name = cluster
s.Update("Attempting to find existing cluster named %q", cluster)
ecsSvc := ecs.New(sess)
desc, err := ecsSvc.DescribeClustersWithContext(ctx, &ecs.DescribeClustersInput{
Clusters: []*string{aws.String(cluster)},
})
if err != nil {
return err
}
for _, c := range desc.Clusters {
if *c.ClusterName == cluster {
if *c.Status == "PROVISIONING" {
s.Update("Existing ecs cluster %q is still provisioning - try again later.", cluster)
} else if *c.Status == "ACTIVE" {
s.Update("Using existing ECS cluster %s", cluster)
if c.ClusterArn != nil {
state.Arn = *c.ClusterArn
}
s.Done()
return nil
} else {
// Warn if we encounter waypoint clusters in other odd states (i.e. DEPROVISIONING, FAILED, etc.)
// I think it's ok to try to create a new cluster if one exists in a non-active non-provisioning state
log.Warn("Ignoring cluster named %q in state %q", cluster, *c.Status)
}
}
}
if p.config.EC2Cluster {
return status.Errorf(codes.FailedPrecondition, "EC2 clusters can not be automatically created")
}
s.Update("No existing cluster found - creating new ECS cluster: %s", cluster)
c, err := ecsSvc.CreateClusterWithContext(ctx, &ecs.CreateClusterInput{
ClusterName: aws.String(cluster),
})
if err != nil {
return err
}
if c.Cluster != nil && c.Cluster.ClusterArn != nil {
state.Arn = *c.Cluster.ClusterArn
}
s.Update("Created ECS cluster: %s", cluster)
s.Done()
return nil
}
func (p *Platform) resourceClusterStatus(
ctx context.Context,
sg terminal.StepGroup,
sess *session.Session,
state *Resource_Cluster,
sr *resource.StatusResponse,
) error {
s := sg.Add("Checking status of the ecs cluster %q...", state.Name)
defer s.Abort()
ecsSvc := ecs.New(sess)
desc, err := ecsSvc.DescribeClustersWithContext(ctx, &ecs.DescribeClustersInput{
Clusters: []*string{aws.String(state.Name)},
})
if err != nil {
return status.Errorf(codes.Internal, "failed to describe cluster named %q (ARN: %q): %s", state.Name, state.Arn, err)
}
clusterResource := sdk.StatusReport_Resource{
Name: state.Name,
}
sr.Resources = append(sr.Resources, &clusterResource)
for _, c := range desc.Clusters {
if *c.ClusterName == state.Name {
s.Update("Found existing ECS cluster: %s", state.Name)
clusterResource.Id = *c.ClusterArn
switch *c.Status {
case "ACTIVE":
clusterResource.Health = sdk.StatusReport_READY
case "PROVISIONING":
clusterResource.Health = sdk.StatusReport_ALIVE
case "DEPROVISIONING", "FAILED", "INACTIVE":
clusterResource.Health = sdk.StatusReport_DOWN
default:
clusterResource.Health = sdk.StatusReport_UNKNOWN
}
clusterResource.HealthMessage = *c.Status
stateJson, err := json.Marshal(c)
if err != nil {
return status.Errorf(codes.Internal, "failed to marshal ecs cluster state json: %s", err)
}
clusterResource.StateJson = string(stateJson)
s.Done()
return nil
}
}
// Failed to find ECS cluster
clusterResource.Health = sdk.StatusReport_MISSING
clusterResource.HealthMessage = fmt.Sprintf("No cluster named %q found (expected arn %q)", state.Name, state.Arn)
s.Update("Done checking ecs cluster status")
s.Done()
return nil
}
func (p *Platform) resourceServiceCreate(
ctx context.Context,
sg terminal.StepGroup,
log hclog.Logger,
sess *session.Session,
src *component.Source,
deploymentId DeploymentId,
state *Resource_Service,
// Outputs of other resource creation processes
taskDefinition *Resource_TaskDefinition,
cluster *Resource_Cluster,
targetGroup *Resource_TargetGroup,
subnets *Resource_ServiceSubnets,
securityGroups *Resource_InternalSecurityGroups,
_ *Resource_Alb_Listener, // Necessary dependency. service creation will fail unless this exists and the target group has been added.
) error {
s := sg.Add("Initiating ecs service creation")
defer s.Abort()
// Use the common deployment ID as our service name
serviceName := string(deploymentId)
// We have to clamp at a length of 32 because the Name field
// requires that the name is 32 characters or less.
if len(serviceName) > 32 {
serviceName = serviceName[:32]
log.Debug("using a shortened value for service name due to AWS's length limits", "serviceName", serviceName)
}
count := int64(p.config.Count)
if count == 0 {
count = 1
}
securityGroupIds := make([]*string, len(securityGroups.SecurityGroups))
for i, securityGroup := range securityGroups.SecurityGroups {
securityGroupIds[i] = &securityGroup.Id
}
subnetIds := make([]*string, len(subnets.Subnets.Subnets))
for i, subnet := range subnets.Subnets.Subnets {
subnetIds[i] = &subnet.Id
}
netCfg := &ecs.AwsVpcConfiguration{
Subnets: subnetIds,
SecurityGroups: securityGroupIds,
}
if !p.config.EC2Cluster {
if p.config.AssignPublicIp == nil {
log.Debug("AssignPublicIp config value not defined - defaulting to true.")
p.config.AssignPublicIp = aws.Bool(true)
}
if *p.config.AssignPublicIp {
netCfg.AssignPublicIp = aws.String("ENABLED")
} else {
netCfg.AssignPublicIp = aws.String("DISABLED")
}
}
state.Cluster = cluster.Name
createServiceInput := &ecs.CreateServiceInput{
Cluster: &cluster.Name,
DesiredCount: aws.Int64(count),
LaunchType: &taskDefinition.Runtime,
ServiceName: aws.String(serviceName),
TaskDefinition: aws.String(taskDefinition.Arn),
NetworkConfiguration: &ecs.NetworkConfiguration{
AwsvpcConfiguration: netCfg,
},
}
if targetGroup.Arn != "" {
log.Debug("Creating ECS service with a load balancer")
createServiceInput.SetLoadBalancers([]*ecs.LoadBalancer{{
ContainerName: aws.String(src.App),
ContainerPort: aws.Int64(targetGroup.Port),
TargetGroupArn: &targetGroup.Arn,
}})
} else {
log.Debug("No target group specified - skipping load balancer config for ECS service")
}
s.Update("Creating ECS Service %s", serviceName)
ecsSvc := ecs.New(sess)
// AWS is eventually consistent so even though we probably created the resources that
// are referenced by the task definition, it can error out if we try to reference those resources
// too quickly. So we're forced to guard actions which reference other AWS services
// with loops like this.
var servOut *ecs.CreateServiceOutput
var err error
OUTER:
for i := 0; i <= awsCreateRetries; i++ {
servOut, err = ecsSvc.CreateServiceWithContext(ctx, createServiceInput)
if err == nil {
break
}
// if we encounter an unrecoverable error, exit and skip this loop
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case "AccessDeniedException", "UnsupportedFeatureException",
"PlatformUnknownException",
"PlatformTaskDefinitionIncompatibilityException":
break OUTER
}
}
s.Update("Failed to register ecs service. Will retry in %d seconds (up to %d more times)\nError: %s", awsCreateRetryIntervalSeconds, awsCreateRetries-i, err)
// otherwise sleep and try again
time.Sleep(awsCreateRetryIntervalSeconds * time.Second)
}
if err != nil {
return status.Errorf(codes.Internal, "failed registering ecs service: %s", err)
}
state.Name = *servOut.Service.ServiceName
state.Arn = *servOut.Service.ServiceArn
s.Update("Created ECS Service %s", serviceName)
s.Done()
return nil
}
func (p *Platform) resourceServiceStatus(
ctx context.Context,
sg terminal.StepGroup,
sess *session.Session,
log hclog.Logger,
state *Resource_Service,
sr *resource.StatusResponse,
) error {
s := sg.Add("Determining status of ecs service %s", state.Name)
defer s.Abort()
ecsSvc := ecs.New(sess)
servicesResp, err := ecsSvc.DescribeServicesWithContext(ctx, &ecs.DescribeServicesInput{
Services: []*string{&state.Name},
Cluster: &state.Cluster,
})
if _, ok := err.(*ecs.ClusterNotFoundException); ok {
sr.Resources = append(sr.Resources, &sdk.StatusReport_Resource{
Name: state.Name,
Id: state.Arn,
Health: sdk.StatusReport_MISSING,
HealthMessage: fmt.Sprintf("Cluster named %q is missing", state.Cluster),
})
s.Done()
return nil
}
if err != nil {
return status.Errorf(codes.Internal, "failed to describe service (ARN %q): %s", state.Arn, err)
}
if len(servicesResp.Services) == 0 {
sr.Resources = append(sr.Resources, &sdk.StatusReport_Resource{
Name: state.Name,
Id: state.Arn,
Health: sdk.StatusReport_MISSING,
HealthMessage: fmt.Sprintf("service %q is missing", state.Name),
})
s.Done()
return nil
}
service := servicesResp.Services[0]
serviceResource := sdk.StatusReport_Resource{
Name: *service.ServiceName,
Id: *service.ServiceArn,
CreatedTime: timestamppb.New(*service.CreatedAt),
PlatformUrl: fmt.Sprintf("https://console.aws.amazon.com/ecs/home?region=%s#/clusters/waypoint/services/%s", p.config.Region, state.Name),
Type: "service",
CategoryDisplayHint: sdk.ResourceCategoryDisplayHint_INSTANCE_MANAGER,
HealthMessage: fmt.Sprintf("service is %q", *service.Status),
}
sr.Resources = append(sr.Resources, &serviceResource)
if *service.Status == "ACTIVE" {
serviceResource.Health = sdk.StatusReport_READY
} else {
serviceResource.Health = sdk.StatusReport_DOWN
serviceResource.HealthMessage = fmt.Sprintf("service is %q", *service.Status)
}
serviceJson, err := json.Marshal(map[string]interface{}{"service": service})
if err != nil {
return status.Errorf(codes.Internal, "failed to marshal service %q (ARN %q) state to json: %s", *service.ServiceName, *service.ServiceArn, err)
}
serviceResource.StateJson = string(serviceJson)
taskArns, err := ecsSvc.ListTasksWithContext(ctx, &ecs.ListTasksInput{
ServiceName: &state.Name,
Cluster: &state.Cluster,
})
if err != nil {
return status.Errorf(codes.Internal, "failed to list tasks for service %q in cluster %q: %s", state.Name, state.Cluster, err)
}
// Insert missing tasks if necessary
missingCount := int(*service.DesiredCount) - len(taskArns.TaskArns)
log.Debug("There are missing tasks. The service may be just starting up.", "missing count", missingCount, "service name", state.Name, "cluster", state.Cluster)
for i := 0; i < missingCount; i++ {
sr.Resources = append(sr.Resources, &sdk.StatusReport_Resource{
Type: "task",
Name: "missing",
ParentResourceId: *service.ServiceArn,
Health: sdk.StatusReport_MISSING,
HealthMessage: fmt.Sprintf("task is missing. The parent service %q may be just starting up at the time of this status check", state.Name),
CategoryDisplayHint: sdk.ResourceCategoryDisplayHint_INSTANCE,
})
}
if len(taskArns.TaskArns) > 0 {
tasks, err := ecsSvc.DescribeTasksWithContext(ctx, &ecs.DescribeTasksInput{
Tasks: taskArns.TaskArns,
Cluster: &state.Cluster,
})
if err != nil {
return status.Errorf(codes.Internal, "failed to describe tasks for service %q in cluster %q: %s", state.Name, state.Cluster, err)
}
for _, task := range tasks.Tasks {
// Determine short task ID
splitArn := strings.Split(*task.TaskArn, "/")
taskId := splitArn[len(splitArn)-1]
taskResource := &sdk.StatusReport_Resource{
Type: "task",
Name: taskId,
ParentResourceId: *service.ServiceArn,
Id: *task.TaskArn,
CategoryDisplayHint: sdk.ResourceCategoryDisplayHint_INSTANCE,
CreatedTime: timestamppb.New(*task.CreatedAt),
PlatformUrl: fmt.Sprintf("https://console.aws.amazon.com/ecs/home?region=%s#/clusters/waypoint/tasks/%s", p.config.Region, taskId),
}
sr.Resources = append(sr.Resources, taskResource)
switch strings.ToLower(*task.LastStatus) {
case "running":
taskResource.Health = sdk.StatusReport_READY
case "provisioning", "pending", "activating":
taskResource.Health = sdk.StatusReport_ALIVE
default:
taskResource.Health = sdk.StatusReport_DOWN
}
taskResource.HealthMessage = fmt.Sprintf("task is %q", *task.LastStatus)
// Find IP address if possible
var ipAddress string
for _, attachment := range task.Attachments {
for _, detail := range attachment.Details {
if *detail.Name == "privateIPv4Address" {
ipAddress = *detail.Value
}
}
}
stateJson, err := json.Marshal(map[string]interface{}{
"ipAddress": ipAddress,
"task": task,
})
if err != nil {
return status.Errorf(codes.Internal, "failed to marshal task (arn %q) state to json: %s", *task.TaskArn, err)
}
taskResource.StateJson = string(stateJson)
}
}
s.Done()
return nil
}
func (p *Platform) resourceServiceDestroy(
ctx context.Context,
sg terminal.StepGroup,
sess *session.Session,
log hclog.Logger,
state *Resource_Service,
workspaceDestroy WorkspaceDestroy,
) error {
if workspaceDestroy {
// Services are destroyed when a deployment is destroyed, not a whole workspace.
return nil
}
log.Debug("deleting ecs service", "arn", state.Arn)
if state.Arn == "" {
log.Debug("Missing ECS Service ARN - it must not have been created successfully. Skipping delete.")
return nil
}
s := sg.Add("Deleting service %s", state.Name)
defer s.Abort()
_, err := ecs.New(sess).DeleteServiceWithContext(ctx, &ecs.DeleteServiceInput{
Cluster: &state.Cluster,
Force: aws.Bool(true),
Service: &state.Arn,
})
if err != nil {