-
Notifications
You must be signed in to change notification settings - Fork 8
/
infra.go
2835 lines (2736 loc) · 79.9 KB
/
infra.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 lib
import (
"context"
"encoding/json"
"fmt"
"os"
"path"
"path/filepath"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/apigatewayv2"
"github.com/aws/aws-sdk-go/service/cloudwatchevents"
"github.com/aws/aws-sdk-go/service/cloudwatchlogs"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/lambda"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/ses"
"github.com/aws/aws-sdk-go/service/sqs"
"gopkg.in/yaml.v3"
)
const (
infraSetTagName = "libaws.infraset"
infraSetNameNone = "none"
)
type InfraListOutput struct {
Account string `yaml:"account"`
Region string `yaml:"region"`
InfraSet map[string]*InfraSet `yaml:"infraset,omitempty"`
}
const (
infraKeyName = "name"
infraKeyLambda = "lambda"
infraKeyS3 = "s3"
infraKeyDynamoDB = "dynamodb"
infraKeySqs = "sqs"
infraKeyKeypair = "keypair"
infraKeyVpc = "vpc"
infraKeyInstanceProfile = "instance-profile"
)
type InfraSet struct {
// infra set name
Name string `yaml:"name,omitempty"`
// lambda
Lambda map[string]*InfraLambda `yaml:"lambda,omitempty"`
// stateful infra
DynamoDB map[string]*InfraDynamoDB `yaml:"dynamodb,omitempty"`
SQS map[string]*InfraSQS `yaml:"sqs,omitempty"`
S3 map[string]*InfraS3 `yaml:"s3,omitempty"`
// ec2 infra
Keypair map[string]*InfraKeypair `yaml:"keypair,omitempty"`
Vpc map[string]*InfraVpc `yaml:"vpc,omitempty"`
InstanceProfile map[string]*InfraInstanceProfile `yaml:"instance-profile,omitempty"`
// "none" infraset gets a few extra slots for resources not associated with any infraset
User map[string]*InfraUser `yaml:"user,omitempty"`
Role map[string]*InfraRole `yaml:"role,omitempty"` // any role not associated with an infraset shows up here
Api map[string]*InfraApi `yaml:"api,omitempty"` // any api not associated with an infraset shows up here
Event map[string]*InfraEvent `yaml:"event,omitempty"` // any event not associated with an infraset shows up here
}
type InfraApi struct {
apiID string
infraSetName string
Dns string `json:"dns,omitempty" yaml:"dns,omitempty"`
Domain string `json:"domain,omitempty" yaml:"domain,omitempty"`
ReadOnlyUrl string `json:"url,omitempty" yaml:"url,omitempty"`
}
type InfraUser struct {
Allow []string `json:"allow,omitempty" yaml:"allow,omitempty"`
Policy []string `json:"policy,omitempty" yaml:"policy,omitempty"`
}
type InfraRole struct {
infraSetName string
Allow []string `json:"allow,omitempty" yaml:"allow,omitempty"`
Policy []string `json:"policy,omitempty" yaml:"policy,omitempty"`
}
const (
infraKeyDynamoDBIndexKey = "key"
infraKeyDynamoDBIndexNonKey = "non-key"
infraKeyDynamoDBIndexAttr = "attr"
)
type InfraDynamoDBIndex struct {
Key []string `json:"key" yaml:"key"`
NonKey []string `json:"non-key,omitempty" yaml:"non-key,omitempty"`
Attrs []string `json:"attr,omitempty" yaml:"attr,omitempty"`
}
const (
infraKeyDynamoDBKey = "key"
infraKeyDynamoDBAttr = "attr"
infraKeyDynamoDBGlobalIndex = "global-index"
infraKeyDynamoDBLocalIndex = "local-index"
)
type InfraDynamoDB struct {
infraSetName string
Key []string `json:"key" yaml:"key"`
Attr []string `json:"attr,omitempty" yaml:"attr,omitempty"`
GlobalIndex map[string]*InfraDynamoDBIndex `json:"global-index,omitempty" yaml:"global-index,omitempty"`
LocalIndex map[string]*InfraDynamoDBIndex `json:"local-index,omitempty" yaml:"local-index,omitempty"`
}
const (
infraKeyKeypairPubkeyContent = "pubkey-content"
)
type InfraKeypair struct {
infraSetName string
PubkeyContent string `json:"pubkey-content" yaml:"pubkey-content"`
}
const (
infraKeyVpcSecurityGroup = "security-group"
infraKeyVpcEC2 = "ec2"
)
type InfraVpc struct {
infraSetName string
SecurityGroup map[string]*InfraSecurityGroup `json:"security-group" yaml:"security-group"`
ReadOnlyEC2 map[string]*InfraEC2 `json:"ec2,omitempty" yaml:"ec2,omitempty"`
}
const (
infraKeySecurityGroupRule = "rule"
)
type InfraSecurityGroup struct {
Rule []string `json:"rule,omitempty" yaml:"rule,omitempty"`
}
const (
infraKeyInstanceProfilePolicy = "policy"
infraKeyInstanceProfileAllow = "allow"
)
type InfraInstanceProfile struct {
infraSetName string
Policy []string `json:"policy,omitempty" yaml:"policy,omitempty"`
Allow []string `json:"allow,omitempty" yaml:"allow,omitempty"`
}
type InfraEC2 struct {
vpcID string
instanceID string
name string
Attr []string `json:"attr,omitempty" yaml:"attr,omitempty"`
Count int `json:"count,omitempty" yaml:"count,omitempty"`
}
const (
infraKeyLambdaName = "name"
infraKeyLambdaEntrypoint = "entrypoint"
infraKeyLambdaPolicy = "policy"
infraKeyLambdaAllow = "allow"
infraKeyLambdaTrigger = "trigger"
infraKeyLambdaAttr = "attr"
infraKeyLambdaRequire = "require"
infraKeyLambdaEnv = "env"
infraKeyLambdaInclude = "include"
)
type InfraLambda struct {
dir string // parent dir of infra.yaml file
runtime string // provided (container) or python (zip) or go (zip)
handler string // "main" (go), "filename.main" (python), or "" (container)
infraSetName string
Name string `json:"name,omitempty" yaml:"name,omitempty"`
Arn string `json:"arn,omitempty" yaml:"arn,omitempty"`
Entrypoint string `json:"entrypoint,omitempty" yaml:"entrypoint,omitempty"`
Policy []string `json:"policy,omitempty" yaml:"policy,omitempty"`
Allow []string `json:"allow,omitempty" yaml:"allow,omitempty"`
Attr []string `json:"attr,omitempty" yaml:"attr,omitempty"`
Require []string `json:"require,omitempty" yaml:"require,omitempty"`
Env []string `json:"env,omitempty" yaml:"env,omitempty"`
Include []string `json:"include,omitempty" yaml:"include,omitempty"`
Trigger []*InfraTrigger `json:"trigger,omitempty" yaml:"trigger,omitempty"`
}
const (
infraKeySQSAttr = "attr"
)
type InfraSQS struct {
infraSetName string
Attr []string `json:"attr,omitempty" yaml:"attr,omitempty"`
}
const (
infraKeyS3Attr = "attr"
)
type InfraS3 struct {
infraSetName string
Attr []string `json:"attr,omitempty" yaml:"attr,omitempty"`
}
type InfraEvent struct {
infraSetName string
Target string `json:"target,omitempty" yaml:"target,omitempty"`
Attr []string `json:"attr,omitempty" yaml:"attr,omitempty"`
}
const (
infraKeyTriggerType = "type"
infraKeyTriggerAttr = "attr"
)
type InfraTrigger struct {
lambdaName string
Type string `json:"type,omitempty" yaml:"type,omitempty"`
Attr []string `json:"attr,omitempty" yaml:"attr,omitempty"`
}
func InfraList(ctx context.Context, filter string, showEnvVarValues bool) (*InfraListOutput, error) {
if doDebug {
d := &Debug{start: time.Now(), name: "InfraList"}
defer d.Log()
}
var err error
lock := &sync.RWMutex{}
infra := &InfraListOutput{
InfraSet: map[string]*InfraSet{},
}
account, err := StsAccount(ctx)
if err != nil {
Logger.Fatal("error: ", err)
}
infra.Account = account
infra.Region = Region()
errs := make(chan error)
count := 0
triggersChan := make(chan *InfraTrigger, 1024)
// list keypair
count++
go func() {
defer func() {
if r := recover(); r != nil {
logRecover(r)
}
}()
keypairs, err := InfraListKeypair(ctx)
if err != nil {
errs <- err
return
}
for name, keypair := range keypairs {
infraSetName := keypair.infraSetName
if infraSetName == "" {
infraSetName = infraSetNameNone
}
if filter != "" && !(strings.Contains(infraSetName, filter) || strings.Contains(name, filter)) {
continue
}
lock.Lock()
if infra.InfraSet[infraSetName] == nil {
infra.InfraSet[infraSetName] = &InfraSet{}
}
if infra.InfraSet[infraSetName].Keypair == nil {
infra.InfraSet[infraSetName].Keypair = map[string]*InfraKeypair{}
}
infra.InfraSet[infraSetName].Keypair[name] = keypair
lock.Unlock()
}
errs <- nil
}()
// list api
count++
go func() {
defer func() {
if r := recover(); r != nil {
logRecover(r)
}
}()
apis, err := InfraListApi(ctx, triggersChan)
if err != nil {
errs <- err
return
}
for name, api := range apis {
infraSetName := api.infraSetName
if infraSetName == "" {
infraSetName = infraSetNameNone
}
if filter != "" && !(strings.Contains(infraSetName, filter) || strings.Contains(name, filter)) {
continue
}
lock.Lock()
if infra.InfraSet[infraSetName] == nil {
infra.InfraSet[infraSetName] = &InfraSet{}
}
if infra.InfraSet[infraSetName].Api == nil {
infra.InfraSet[infraSetName].Api = map[string]*InfraApi{}
}
infra.InfraSet[infraSetName].Api[name] = api
lock.Unlock()
}
errs <- nil
}()
// list dynamo
count++
go func() {
defer func() {
if r := recover(); r != nil {
logRecover(r)
}
}()
tables, err := InfraListDynamoDB(ctx)
if err != nil {
errs <- err
return
}
for name, table := range tables {
infraSetName := table.infraSetName
if infraSetName == "" {
infraSetName = infraSetNameNone
}
if filter != "" && !(strings.Contains(infraSetName, filter) || strings.Contains(name, filter)) {
continue
}
lock.Lock()
if infra.InfraSet[infraSetName] == nil {
infra.InfraSet[infraSetName] = &InfraSet{}
}
if infra.InfraSet[infraSetName].DynamoDB == nil {
infra.InfraSet[infraSetName].DynamoDB = map[string]*InfraDynamoDB{}
}
infra.InfraSet[infraSetName].DynamoDB[name] = table
lock.Unlock()
}
errs <- nil
}()
// list vpc
count++
go func() {
defer func() {
if r := recover(); r != nil {
logRecover(r)
}
}()
vpcs, err := InfraListVpc(ctx)
if err != nil {
errs <- err
return
}
for name, vpc := range vpcs {
infraSetName := vpc.infraSetName
if infraSetName == "" {
infraSetName = infraSetNameNone
}
if filter != "" && !(strings.Contains(infraSetName, filter) || strings.Contains(name, filter)) {
continue
}
lock.Lock()
if infra.InfraSet[infraSetName] == nil {
infra.InfraSet[infraSetName] = &InfraSet{}
}
if infra.InfraSet[infraSetName].Vpc == nil {
infra.InfraSet[infraSetName].Vpc = map[string]*InfraVpc{}
}
infra.InfraSet[infraSetName].Vpc[name] = vpc
lock.Unlock()
}
errs <- nil
}()
// list sqs
count++
go func() {
defer func() {
if r := recover(); r != nil {
logRecover(r)
}
}()
queues, err := InfraListSQS(ctx)
if err != nil {
errs <- err
return
}
for name, queue := range queues {
infraSetName := queue.infraSetName
if infraSetName == "" {
infraSetName = infraSetNameNone
}
if filter != "" && !(strings.Contains(infraSetName, filter) || strings.Contains(name, filter)) {
continue
}
lock.Lock()
if infra.InfraSet[infraSetName] == nil {
infra.InfraSet[infraSetName] = &InfraSet{}
}
if infra.InfraSet[infraSetName].SQS == nil {
infra.InfraSet[infraSetName].SQS = map[string]*InfraSQS{}
}
infra.InfraSet[infraSetName].SQS[name] = queue
lock.Unlock()
}
errs <- nil
}()
// list s3
count++
go func() {
defer func() {
if r := recover(); r != nil {
logRecover(r)
}
}()
buckets, err := InfraListS3(ctx, triggersChan)
if err != nil {
errs <- err
return
}
for name, bucket := range buckets {
infraSetName := bucket.infraSetName
if infraSetName == "" {
infraSetName = infraSetNameNone
}
if filter != "" && !(strings.Contains(infraSetName, filter) || strings.Contains(name, filter)) {
continue
}
lock.Lock()
if infra.InfraSet[infraSetName] == nil {
infra.InfraSet[infraSetName] = &InfraSet{}
}
if infra.InfraSet[infraSetName].S3 == nil {
infra.InfraSet[infraSetName].S3 = map[string]*InfraS3{}
}
infra.InfraSet[infraSetName].S3[name] = bucket
lock.Unlock()
}
errs <- nil
}()
// list event triggers
count++
go func() {
defer func() {
if r := recover(); r != nil {
logRecover(r)
}
}()
events, err := InfraListEvent(ctx, triggersChan)
if err != nil {
errs <- err
return
}
for name, event := range events {
infraSetName := event.infraSetName
if infraSetName == "" {
infraSetName = infraSetNameNone
}
if filter != "" && !(strings.Contains(infraSetName, filter) || strings.Contains(name, filter)) {
continue
}
lock.Lock()
if infra.InfraSet[infraSetName] == nil {
infra.InfraSet[infraSetName] = &InfraSet{}
}
if infra.InfraSet[infraSetName].Event == nil {
infra.InfraSet[infraSetName].Event = map[string]*InfraEvent{}
}
infra.InfraSet[infraSetName].Event[name] = event
lock.Unlock()
}
errs <- nil
}()
// list user
count++
go func() {
defer func() {
if r := recover(); r != nil {
logRecover(r)
}
}()
users, err := InfraListUser(ctx)
if err != nil {
errs <- err
return
}
lock.Lock()
if infra.InfraSet[infraSetNameNone] == nil {
infra.InfraSet[infraSetNameNone] = &InfraSet{}
}
if infra.InfraSet[infraSetNameNone].User == nil {
infra.InfraSet[infraSetNameNone].User = map[string]*InfraUser{}
}
for name, user := range users {
infra.InfraSet[infraSetNameNone].User[name] = user
}
lock.Unlock()
errs <- nil
}()
// list role
count++
go func() {
defer func() {
if r := recover(); r != nil {
logRecover(r)
}
}()
roles, err := InfraListRole(ctx)
if err != nil {
errs <- err
return
}
for name, role := range roles {
infraSetName := role.infraSetName
if infraSetName == "" {
infraSetName = infraSetNameNone
}
if filter != "" && !(strings.Contains(infraSetName, filter) || strings.Contains(name, filter)) {
continue
}
lock.Lock()
if infra.InfraSet[infraSetName] == nil {
infra.InfraSet[infraSetName] = &InfraSet{}
}
if infra.InfraSet[infraSetName].Role == nil {
infra.InfraSet[infraSetName].Role = map[string]*InfraRole{}
}
infra.InfraSet[infraSetName].Role[name] = role
lock.Unlock()
}
errs <- nil
}()
// list instance profile
count++
go func() {
defer func() {
if r := recover(); r != nil {
logRecover(r)
}
}()
profiles, err := InfraListInstanceProfile(ctx)
if err != nil {
errs <- err
return
}
for name, profile := range profiles {
infraSetName := profile.infraSetName
if infraSetName == "" {
infraSetName = infraSetNameNone
}
if filter != "" && !(strings.Contains(infraSetName, filter) || strings.Contains(name, filter)) {
continue
}
lock.Lock()
if infra.InfraSet[infraSetName] == nil {
infra.InfraSet[infraSetName] = &InfraSet{}
}
if infra.InfraSet[infraSetName].InstanceProfile == nil {
infra.InfraSet[infraSetName].InstanceProfile = map[string]*InfraInstanceProfile{}
}
infra.InfraSet[infraSetName].InstanceProfile[name] = profile
lock.Unlock()
}
errs <- nil
}()
// list lambda
lambdaErr := make(chan error)
go func() {
defer func() {
if r := recover(); r != nil {
logRecover(r)
}
}()
lambdas, err := InfraListLambda(ctx, triggersChan, filter)
if err != nil {
lambdaErr <- err
return
}
for name, lambda := range lambdas {
lambda.Name = "" // name is not a private field on lambda, we don't want this exported as yaml/json
infraSetName := lambda.infraSetName
if infraSetName == "" {
infraSetName = infraSetNameNone
}
lock.Lock()
if infra.InfraSet[infraSetName] == nil {
infra.InfraSet[infraSetName] = &InfraSet{}
}
if infra.InfraSet[infraSetName].Lambda == nil {
infra.InfraSet[infraSetName].Lambda = map[string]*InfraLambda{}
}
infra.InfraSet[infraSetName].Lambda[name] = lambda
lock.Unlock()
}
lambdaErr <- nil
}()
for i := 0; i < count; i++ {
err := <-errs
if err != nil {
Logger.Fatal("error: ", err)
}
}
close(triggersChan)
err = <-lambdaErr
if err != nil {
Logger.Fatal("error: ", err)
}
// remove resources which are implicit to an existing lambda
var instanceProfileNames []string
var lambdaNames []string
var websocketNames []string
for _, infraSet := range infra.InfraSet {
if infraSet.Name == infraSetNameNone {
continue
}
for name := range infraSet.Lambda {
lambdaNames = append(lambdaNames, name)
websocketNames = append(websocketNames, name+LambdaWebsocketSuffix)
}
for name := range infraSet.InstanceProfile {
instanceProfileNames = append(instanceProfileNames, name)
}
}
for _, infraSet := range infra.InfraSet {
if infraSet.Name == infraSetNameNone {
continue
}
for _, vpc := range infraSet.Vpc {
for sgName, sg := range vpc.SecurityGroup {
if sgName == "default" && len(sg.Rule) == 0 {
delete(vpc.SecurityGroup, sgName) // do not show empty default sg
}
}
for _, ec2 := range vpc.ReadOnlyEC2 {
var attrs []string
for _, attr := range ec2.Attr {
if !strings.HasPrefix(attr, "vpc=") && !strings.HasPrefix(attr, "tag.user=") {
attrs = append(attrs, attr) // these attrs are important for instance grouping, but needn't be shown
}
}
ec2.Attr = attrs
}
}
for name := range infraSet.Event {
if Contains(lambdaNames, strings.Split(name, lambdaEventRuleNameSeparator)[0]) {
delete(infraSet.Event, name) // shown as trigger of the lambda
}
}
for name := range infraSet.Api {
if Contains(lambdaNames, name) || Contains(websocketNames, name) {
delete(infraSet.Api, name) // shown as trigger of the lambda
}
}
for name := range infraSet.Role {
if Contains(lambdaNames, name) {
delete(infraSet.Role, name) // shown as allows/policies of the lambda
}
if Contains(instanceProfileNames, name) {
delete(infraSet.Role, name) // shown as instanceProfile
}
if name == "OrganizationAccountAccessRole" {
delete(infraSet.Role, name) // ignore always present roles
}
}
if !showEnvVarValues {
for _, infraLambda := range infraSet.Lambda {
for i, env := range infraLambda.Env {
k, v, err := SplitOnce(env, "=")
if err != nil {
Logger.Println("error:", err)
return nil, err
}
infraLambda.Env[i] = k + "=" + sha256Short([]byte(v))
}
}
}
}
if filter != "" {
infra.InfraSet[infraSetNameNone] = nil
}
return infra, nil
}
func InfraListEvent(ctx context.Context, triggersChan chan<- *InfraTrigger) (map[string]*InfraEvent, error) {
if doDebug {
d := &Debug{start: time.Now(), name: "InfraListEvent"}
defer d.Log()
}
results := make(map[string]*InfraEvent)
lock := sync.RWMutex{}
rules, err := EventsListRules(ctx, nil)
if err != nil {
Logger.Println("error:", err)
return nil, err
}
errChan := make(chan error)
for _, rule := range rules {
rule := rule
go func() {
defer func() {
if r := recover(); r != nil {
logRecover(r)
}
}()
targets, err := EventsListRuleTargets(ctx, *rule.Name, nil)
if err != nil {
Logger.Println("error:", err)
errChan <- err
return
}
tagsOut, err := EventsClient().ListTagsForResourceWithContext(ctx, &cloudwatchevents.ListTagsForResourceInput{
ResourceARN: rule.Arn,
})
if err != nil {
Logger.Println("error:", err)
errChan <- err
return
}
infraSetName := ""
for _, tag := range tagsOut.Tags {
if *tag.Key == infraSetTagName {
infraSetName = *tag.Value
break
}
}
for _, target := range targets {
if strings.HasPrefix(*target.Arn, "arn:aws:lambda:") {
if rule.ScheduleExpression != nil {
triggersChan <- &InfraTrigger{
lambdaName: Last(strings.Split(*target.Arn, ":")),
Type: lambdaTriggerSchedule,
Attr: []string{*rule.ScheduleExpression},
}
} else if rule.EventPattern != nil && *rule.EventPattern == lambdaEcrEventPattern {
triggersChan <- &InfraTrigger{
lambdaName: Last(strings.Split(*target.Arn, ":")),
Type: lambdaTriggerEcr,
}
}
if rule.Name == nil {
rule.Name = aws.String("-")
}
if rule.EventPattern == nil {
rule.EventPattern = aws.String("-")
}
if target.Arn == nil {
target.Arn = aws.String("-")
}
infraEvent := &InfraEvent{
infraSetName: infraSetName,
Target: *target.Arn,
Attr: []string{"eventpattern=" + *rule.EventPattern, "target=" + *target.Arn},
}
lock.Lock()
results[*rule.Name] = infraEvent
lock.Unlock()
}
}
errChan <- nil
}()
}
for range rules {
err := <-errChan
if err != nil {
Logger.Println("error:", err)
return nil, err
}
}
return results, nil
}
func InfraListLambda(ctx context.Context, triggersChan <-chan *InfraTrigger, filter string) (map[string]*InfraLambda, error) {
if doDebug {
d := &Debug{start: time.Now(), name: "InfraListLambda"}
defer d.Log()
}
allFns, err := LambdaListFunctions(ctx)
if err != nil {
Logger.Println("error:", err)
return nil, err
}
var fns []*lambda.FunctionConfiguration
for _, fn := range allFns {
if filter != "" && !strings.Contains(*fn.FunctionName, filter) {
continue
}
fns = append(fns, fn)
}
errChan := make(chan error)
triggers := make(map[string][]*InfraTrigger)
res := make(map[string]*InfraLambda)
for _, fn := range fns {
fn := fn
go func() {
defer func() {
if r := recover(); r != nil {
logRecover(r)
}
}()
infraLambda := &InfraLambda{
Name: *fn.FunctionName,
}
if fn.Environment != nil {
for k, v := range fn.Environment.Variables {
if v != nil {
infraLambda.Env = append(infraLambda.Env, k+"="+*v)
}
}
}
sort.Strings(infraLambda.Env)
tagsOut, err := LambdaClient().ListTagsWithContext(ctx, &lambda.ListTagsInput{
Resource: fn.FunctionArn,
})
if err != nil {
Logger.Println("error:", err)
errChan <- err
return
}
for k, v := range tagsOut.Tags {
if k == infraSetTagName {
infraLambda.infraSetName = *v
break
}
}
res[infraLambda.Name] = infraLambda
if *fn.MemorySize != lambdaAttrMemoryDefault {
infraLambda.Attr = append(infraLambda.Attr, fmt.Sprintf("memory=%d", *fn.MemorySize))
}
if *fn.Timeout != lambdaAttrTimeoutDefault {
infraLambda.Attr = append(infraLambda.Attr, fmt.Sprintf("timeout=%d", *fn.Timeout))
}
out, err := LambdaClient().GetFunctionConcurrencyWithContext(ctx, &lambda.GetFunctionConcurrencyInput{
FunctionName: aws.String(*fn.FunctionName),
})
if err != nil {
Logger.Println("error:", err)
errChan <- err
return
}
if out.ReservedConcurrentExecutions != nil {
infraLambda.Attr = append(infraLambda.Attr, fmt.Sprintf("concurrency=%d", *out.ReservedConcurrentExecutions))
}
logGroupName := "/aws/lambda/" + *fn.FunctionName
outGroups, err := LogsClient().DescribeLogGroupsWithContext(ctx, &cloudwatchlogs.DescribeLogGroupsInput{
LogGroupNamePrefix: aws.String(logGroupName),
})
if err != nil {
Logger.Println("error:", err)
errChan <- err
return
}
var logGroup *cloudwatchlogs.LogGroup
for _, lg := range outGroups.LogGroups {
if logGroupName == *lg.LogGroupName {
logGroup = lg
break
}
}
if logGroup != nil {
if logGroup.RetentionInDays == nil {
infraLambda.Attr = append(infraLambda.Attr, "logs-ttl-days=0")
} else if int(*logGroup.RetentionInDays) != lambdaAttrLogsTTLDaysDefault {
infraLambda.Attr = append(infraLambda.Attr, fmt.Sprintf("logs-ttl-days=%d", *logGroup.RetentionInDays))
}
}
roleName := Last(strings.Split(*fn.Role, "/"))
policies, err := IamListRolePolicies(ctx, roleName)
if err != nil {
errChan <- err
return
}
for _, policy := range policies {
infraLambda.Policy = append(infraLambda.Policy, *policy.PolicyName)
}
allows, err := IamListRoleAllows(ctx, roleName)
if err != nil {
errChan <- err
return
}
for _, allow := range allows {
infraLambda.Allow = append(infraLambda.Allow, allow.String())
}
rules, err := SesListReceiptRulesets(ctx)
if err != nil {
errChan <- err
return
}
for _, rule := range rules {
out, err := SesClient().DescribeReceiptRuleWithContext(ctx, &ses.DescribeReceiptRuleInput{
RuleName: rule.Name,
RuleSetName: rule.Name,
})
if err == nil {
bucket := ""
prefix := ""
dns := ""
for _, action := range out.Rule.Actions {
if action.S3Action != nil {
if action.S3Action.BucketName != nil {
bucket = *action.S3Action.BucketName
}
if action.S3Action.ObjectKeyPrefix != nil {
prefix = *action.S3Action.ObjectKeyPrefix
}
}
if action.LambdaAction != nil &&
action.LambdaAction.FunctionArn != nil &&
*action.LambdaAction.FunctionArn == *fn.FunctionArn &&
len(out.Rule.Recipients) == 1 &&
*out.Rule.Recipients[0] == *rule.Name {
dns = *rule.Name
}
}
attrs := []string{
"dns=" + dns,
"bucket=" + bucket,
}
if prefix != "" {
attrs = append(attrs, "prefix="+prefix)
}
triggers[*fn.FunctionName] = append(triggers[*fn.FunctionName], &InfraTrigger{
lambdaName: *fn.FunctionName,
Type: lambdaTriggerSes,
Attr: attrs,
})
}
}
var marker *string
for {
out, err := LambdaClient().ListEventSourceMappingsWithContext(ctx, &lambda.ListEventSourceMappingsInput{
FunctionName: fn.FunctionArn,
Marker: marker,
})
if err != nil {
Logger.Println("error:", err)
errChan <- err
return
}
for _, mapping := range out.EventSourceMappings {
if Contains([]string{"Disabled", "Disabling"}, *mapping.State) {
continue
}
infra := ArnToInfraName(*mapping.EventSourceArn)
switch infra {
case lambdaTriggerDynamoDB:
triggers[*fn.FunctionName] = append(triggers[*fn.FunctionName], &InfraTrigger{
lambdaName: *fn.FunctionName,
Type: infra,
Attr: []string{
DynamoDBStreamArnToTableName(*mapping.EventSourceArn),
fmt.Sprintf("batch=%d", *mapping.BatchSize),
fmt.Sprintf("parallel=%d", *mapping.ParallelizationFactor),
fmt.Sprintf("retry=%d", *mapping.MaximumRetryAttempts),
fmt.Sprintf("start=%s", strings.ToLower(*mapping.StartingPosition)),
fmt.Sprintf("window=%d", *mapping.MaximumBatchingWindowInSeconds),
},
})
case lambdaTriggerSQS:
triggers[*fn.FunctionName] = append(triggers[*fn.FunctionName], &InfraTrigger{
lambdaName: *fn.FunctionName,
Type: infra,
Attr: []string{
SQSArnToName(*mapping.EventSourceArn),
fmt.Sprintf("batch=%d", *mapping.BatchSize),