forked from wallix/awless
-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert.go
693 lines (631 loc) · 22.4 KB
/
convert.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
/*
Copyright 2017 WALLIX
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package awsconv
import (
"bytes"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"hash/adler32"
"net"
"net/url"
"reflect"
"sync"
"time"
awssdk "github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/acm"
"github.com/aws/aws-sdk-go/service/autoscaling"
"github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/aws/aws-sdk-go/service/cloudfront"
"github.com/aws/aws-sdk-go/service/cloudwatch"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ecr"
"github.com/aws/aws-sdk-go/service/ecs"
"github.com/aws/aws-sdk-go/service/elb"
"github.com/aws/aws-sdk-go/service/elbv2"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/lambda"
"github.com/aws/aws-sdk-go/service/rds"
"github.com/aws/aws-sdk-go/service/route53"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/sns"
"github.com/wallix/awless/cloud"
"github.com/wallix/awless/cloud/properties"
"github.com/wallix/awless/graph"
)
func InitResource(source interface{}) (*graph.Resource, error) {
var res *graph.Resource
switch ss := source.(type) {
// EC2
case *ec2.Instance:
res = graph.InitResource(cloud.Instance, awssdk.StringValue(ss.InstanceId))
case *ec2.Vpc:
res = graph.InitResource(cloud.Vpc, awssdk.StringValue(ss.VpcId))
case *ec2.Subnet:
res = graph.InitResource(cloud.Subnet, awssdk.StringValue(ss.SubnetId))
case *ec2.SecurityGroup:
res = graph.InitResource(cloud.SecurityGroup, awssdk.StringValue(ss.GroupId))
case *ec2.KeyPairInfo:
res = graph.InitResource(cloud.Keypair, awssdk.StringValue(ss.KeyName))
case *ec2.Volume:
res = graph.InitResource(cloud.Volume, awssdk.StringValue(ss.VolumeId))
case *ec2.Image:
res = graph.InitResource(cloud.Image, awssdk.StringValue(ss.ImageId))
case *ec2.ImportImageTask:
res = graph.InitResource(cloud.ImportImageTask, awssdk.StringValue(ss.ImportTaskId))
case *ec2.InternetGateway:
res = graph.InitResource(cloud.InternetGateway, awssdk.StringValue(ss.InternetGatewayId))
case *ec2.NatGateway:
res = graph.InitResource(cloud.NatGateway, awssdk.StringValue(ss.NatGatewayId))
case *ec2.RouteTable:
res = graph.InitResource(cloud.RouteTable, awssdk.StringValue(ss.RouteTableId))
case *ec2.AvailabilityZone:
res = graph.InitResource(cloud.AvailabilityZone, awssdk.StringValue(ss.ZoneName))
case *ec2.Address:
if awssdk.StringValue(ss.AllocationId) != "" {
res = graph.InitResource(cloud.ElasticIP, awssdk.StringValue(ss.AllocationId))
} else {
res = graph.InitResource(cloud.ElasticIP, awssdk.StringValue(ss.PublicIp))
}
case *ec2.Snapshot:
res = graph.InitResource(cloud.Snapshot, awssdk.StringValue(ss.SnapshotId))
case *ec2.NetworkInterface:
res = graph.InitResource(cloud.NetworkInterface, awssdk.StringValue(ss.NetworkInterfaceId))
// Loadbalancer
case *elb.LoadBalancerDescription:
res = graph.InitResource(cloud.ClassicLoadBalancer, awssdk.StringValue(ss.LoadBalancerName))
case *elbv2.LoadBalancer:
res = graph.InitResource(cloud.LoadBalancer, awssdk.StringValue(ss.LoadBalancerArn))
case *elbv2.TargetGroup:
res = graph.InitResource(cloud.TargetGroup, awssdk.StringValue(ss.TargetGroupArn))
case *elbv2.Listener:
res = graph.InitResource(cloud.Listener, awssdk.StringValue(ss.ListenerArn))
// Database
case *rds.DBInstance:
res = graph.InitResource(cloud.Database, awssdk.StringValue(ss.DBInstanceIdentifier))
case *rds.DBSubnetGroup:
res = graph.InitResource(cloud.DbSubnetGroup, awssdk.StringValue(ss.DBSubnetGroupArn))
// Autoscaling
case *autoscaling.LaunchConfiguration:
res = graph.InitResource(cloud.LaunchConfiguration, awssdk.StringValue(ss.LaunchConfigurationARN))
case *autoscaling.Group:
res = graph.InitResource(cloud.ScalingGroup, awssdk.StringValue(ss.AutoScalingGroupARN))
case *autoscaling.ScalingPolicy:
res = graph.InitResource(cloud.ScalingPolicy, awssdk.StringValue(ss.PolicyARN))
// Container
case *ecr.Repository:
res = graph.InitResource(cloud.Repository, awssdk.StringValue(ss.RepositoryArn))
case *ecs.Cluster:
res = graph.InitResource(cloud.ContainerCluster, awssdk.StringValue(ss.ClusterArn))
case *ecs.TaskDefinition:
res = graph.InitResource(cloud.ContainerTask, awssdk.StringValue(ss.TaskDefinitionArn))
case *ecs.Container:
res = graph.InitResource(cloud.Container, awssdk.StringValue(ss.ContainerArn))
case *ecs.ContainerInstance:
res = graph.InitResource(cloud.ContainerInstance, awssdk.StringValue(ss.ContainerInstanceArn))
// ACM
case *acm.CertificateSummary:
res = graph.InitResource(cloud.Certificate, awssdk.StringValue(ss.CertificateArn))
// IAM
case *iam.User:
res = graph.InitResource(cloud.User, awssdk.StringValue(ss.UserId))
case *iam.UserDetail:
res = graph.InitResource(cloud.User, awssdk.StringValue(ss.UserId))
case *iam.RoleDetail:
res = graph.InitResource(cloud.Role, awssdk.StringValue(ss.RoleId))
case *iam.GroupDetail:
res = graph.InitResource(cloud.Group, awssdk.StringValue(ss.GroupId))
case *iam.Policy:
res = graph.InitResource(cloud.Policy, awssdk.StringValue(ss.PolicyId))
case *iam.ManagedPolicyDetail:
res = graph.InitResource(cloud.Policy, awssdk.StringValue(ss.PolicyId))
case *iam.AccessKeyMetadata:
res = graph.InitResource(cloud.AccessKey, awssdk.StringValue(ss.AccessKeyId))
case *iam.InstanceProfile:
res = graph.InitResource(cloud.InstanceProfile, awssdk.StringValue(ss.InstanceProfileId))
case *iam.VirtualMFADevice:
res = graph.InitResource(cloud.MFADevice, awssdk.StringValue(ss.SerialNumber))
// S3
case *s3.Bucket:
res = graph.InitResource(cloud.Bucket, awssdk.StringValue(ss.Name))
case *s3.Object:
res = graph.InitResource(cloud.S3Object, awssdk.StringValue(ss.Key))
//SNS
case *sns.Subscription:
res = graph.InitResource(cloud.Subscription, awssdk.StringValue(ss.Endpoint))
case *sns.Topic:
res = graph.InitResource(cloud.Topic, awssdk.StringValue(ss.TopicArn))
// DNS
case *route53.HostedZone:
res = graph.InitResource(cloud.Zone, awssdk.StringValue(ss.Id))
case *route53.ResourceRecordSet:
id := HashFields(awssdk.StringValue(ss.Name), awssdk.StringValue(ss.Type))
res = graph.InitResource(cloud.Record, id)
// Lambda
case *lambda.FunctionConfiguration:
res = graph.InitResource(cloud.Function, awssdk.StringValue(ss.FunctionArn))
// Monitoring
case *cloudwatch.Metric:
id := HashFields(awssdk.StringValue(ss.Namespace), awssdk.StringValue(ss.MetricName))
res = graph.InitResource(cloud.Metric, id)
case *cloudwatch.MetricAlarm:
res = graph.InitResource(cloud.Alarm, awssdk.StringValue(ss.AlarmArn))
// cdn
case *cloudfront.DistributionSummary:
res = graph.InitResource(cloud.Distribution, awssdk.StringValue(ss.Id))
// cloudformation
case *cloudformation.Stack:
res = graph.InitResource(cloud.Stack, awssdk.StringValue(ss.StackId))
default:
return nil, fmt.Errorf("Unknown type of resource %T", source)
}
return res, nil
}
func NewResource(source interface{}) (*graph.Resource, error) {
res, err := InitResource(source)
if err != nil {
return res, err
}
res.Properties()[properties.ID] = res.Id()
value := reflect.ValueOf(source)
if !value.IsValid() || value.Kind() != reflect.Ptr || value.IsNil() {
return nil, fmt.Errorf("can not fetch cloud resource. %v is not a valid pointer.", value)
}
nodeV := value.Elem()
type keyValResult struct {
key string
val interface{}
}
resultc := make(chan keyValResult)
errc := make(chan error)
var wg sync.WaitGroup
for prop, trans := range awsResourcesDef[res.Type()] {
wg.Add(1)
go func(p string, t *propertyTransform) {
defer wg.Done()
if t.transform != nil {
sourceField := nodeV.FieldByName(t.name)
if sourceField.IsValid() && !sourceField.IsNil() {
val, err := t.transform(sourceField.Interface())
if err == ErrTagNotFound {
return
}
if err != nil {
errc <- fmt.Errorf("type [%s]: prop '%v': %s", res.Type(), p, err)
}
resultc <- keyValResult{p, val}
}
}
if t.fetch != nil {
val, err := t.fetch(source)
if err != nil {
errc <- fmt.Errorf("type [%s]: prop '%v': %s", res.Type(), p, err)
}
resultc <- keyValResult{p, val}
}
}(prop, trans)
}
go func() {
wg.Wait()
close(errc)
close(resultc)
}()
for {
select {
case e := <-errc:
if e != nil {
return res, e
}
case keyVal, ok := <-resultc:
if !ok {
return res, nil
}
res.Properties()[keyVal.key] = keyVal.val
}
}
}
var ErrTagNotFound = errors.New("aws tag key not found")
type propertyTransform struct {
name string
transform transformFn
fetch fetchFn
}
type transformFn func(i interface{}) (interface{}, error)
type fetchFn func(i interface{}) (interface{}, error)
var extractValueFn = func(i interface{}) (interface{}, error) {
iv := reflect.ValueOf(i)
if iv.Kind() == reflect.Ptr {
if iv.IsNil() {
return nil, nil
}
return iv.Elem().Interface(), nil
}
switch ii := i.(type) {
case []*string:
return awssdk.StringValueSlice(ii), nil
}
return nil, fmt.Errorf("extract value: not a pointer but a %T", i)
}
var extractValueAsStringFn = func(i interface{}) (interface{}, error) {
val, err := extractValueFn(i)
return fmt.Sprint(val), err
}
// Extract time forcing timezone to UTC (friendlier when running test in different timezones i.e. travis)
var extractTimeFn = func(i interface{}) (interface{}, error) {
t, ok := i.(*time.Time)
if ok {
return t.UTC(), nil
}
s, ok := i.(*string)
if ok {
t, err := time.Parse("2006-01-02T15:04:05.000+0000", awssdk.StringValue(s))
if err != nil {
return nil, err
}
return t.UTC(), nil
}
return nil, fmt.Errorf("extract time: expected time pointer, got: %T", i)
}
// Extract time that have a Z directly after the time without a space which means UTC
// (https://en.wikipedia.org/wiki/ISO_8601#UTC)
var extractTimeWithZSuffixFn = func(i interface{}) (interface{}, error) {
t, ok := i.(*time.Time)
if ok {
return t.UTC(), nil
}
s, ok := i.(*string)
if ok {
t, err := time.Parse("2006-01-02T15:04:05.000Z", awssdk.StringValue(s))
if err != nil {
return nil, err
}
return t, nil
}
return nil, fmt.Errorf("extract time: expected time pointer, got: %T", i)
}
var extractIpPermissionSliceFn = func(i interface{}) (interface{}, error) {
if _, ok := i.([]*ec2.IpPermission); !ok {
return nil, fmt.Errorf("extract ip permission: not a permission slice but a %T", i)
}
var rules []*graph.FirewallRule
for _, ipPerm := range i.([]*ec2.IpPermission) {
rule := &graph.FirewallRule{}
protocol := awssdk.StringValue(ipPerm.IpProtocol)
switch protocol {
case "-1":
rule.Protocol = "any"
rule.PortRange = graph.PortRange{Any: true}
case "tcp", "udp", "icmp", "58":
rule.Protocol = protocol
fromPort := awssdk.Int64Value(ipPerm.FromPort)
toPort := awssdk.Int64Value(ipPerm.ToPort)
if fromPort == -1 || toPort == -1 {
rule.PortRange = graph.PortRange{Any: true}
} else {
rule.PortRange = graph.PortRange{FromPort: fromPort, ToPort: toPort}
}
default:
rule.Protocol = protocol
rule.PortRange = graph.PortRange{Any: true}
}
for _, r := range ipPerm.IpRanges {
_, net, err := net.ParseCIDR(awssdk.StringValue(r.CidrIp))
if err != nil {
return rules, err
}
rule.IPRanges = append(rule.IPRanges, net)
}
for _, r := range ipPerm.Ipv6Ranges {
_, net, err := net.ParseCIDR(awssdk.StringValue(r.CidrIpv6))
if err != nil {
return rules, err
}
rule.IPRanges = append(rule.IPRanges, net)
}
for _, group := range ipPerm.UserIdGroupPairs {
rule.Sources = append(rule.Sources, awssdk.StringValue(group.GroupId))
}
rules = append(rules, rule)
}
return rules, nil
}
var extractNameValueFn = func(i interface{}) (interface{}, error) {
if _, ok := i.([]*cloudwatch.Dimension); !ok {
return nil, fmt.Errorf("extract ip namevalue: not a dimension slice but a %T", i)
}
var nameValues []*graph.KeyValue
for _, dimension := range i.([]*cloudwatch.Dimension) {
keyval := &graph.KeyValue{KeyName: awssdk.StringValue(dimension.Name), Value: awssdk.StringValue(dimension.Value)}
nameValues = append(nameValues, keyval)
}
return nameValues, nil
}
var extractECSAttributesFn = func(i interface{}) (interface{}, error) {
if _, ok := i.([]*ecs.Attribute); !ok {
return nil, fmt.Errorf("extract ECS attributes: not an attribute slice but a %T", i)
}
var keyVals []*graph.KeyValue
for _, attribute := range i.([]*ecs.Attribute) {
keyval := &graph.KeyValue{KeyName: awssdk.StringValue(attribute.Name), Value: awssdk.StringValue(attribute.Value)}
keyVals = append(keyVals, keyval)
}
return keyVals, nil
}
var extractRouteTableAssociationsFn = func(i interface{}) (interface{}, error) {
if _, ok := i.([]*ec2.RouteTableAssociation); !ok {
return nil, fmt.Errorf("extract route table associations: not an association slice but a %T", i)
}
var keyVals []*graph.KeyValue
for _, assoc := range i.([]*ec2.RouteTableAssociation) {
keyval := &graph.KeyValue{KeyName: awssdk.StringValue(assoc.RouteTableAssociationId), Value: awssdk.StringValue(assoc.SubnetId)}
keyVals = append(keyVals, keyval)
}
return keyVals, nil
}
var extractFieldFn = func(field string) transformFn {
return func(i interface{}) (interface{}, error) {
value := reflect.ValueOf(i)
if value.Kind() != reflect.Ptr {
return nil, fmt.Errorf("extract field '%s': not a pointer but a %T", field, i)
}
struc := value.Elem()
if struc.Kind() != reflect.Struct {
return nil, fmt.Errorf("extract field '%s': not a struct pointer but a %T", field, i)
}
structField := struc.FieldByName(field)
if !structField.IsValid() {
return nil, fmt.Errorf("extract field: field not found: %s", field)
}
return extractValueFn(structField.Interface())
}
}
var extractTagsFn = func(i interface{}) (interface{}, error) {
var out []string
switch tags := i.(type) {
case []*ec2.Tag:
for _, t := range tags {
out = append(out, fmt.Sprintf("%s=%s", awssdk.StringValue(t.Key), awssdk.StringValue(t.Value)))
}
case []*autoscaling.TagDescription:
for _, t := range tags {
out = append(out, fmt.Sprintf("%s=%s", awssdk.StringValue(t.Key), awssdk.StringValue(t.Value)))
}
default:
return nil, fmt.Errorf("extract tags: not a tag slice, but a %T", i)
}
return out, nil
}
var extractTagFn = func(key string) transformFn {
return func(i interface{}) (interface{}, error) {
tags, ok := i.([]*ec2.Tag)
if !ok {
return nil, fmt.Errorf("extract tag: not a tag slice, but a %T", i)
}
for _, t := range tags {
if key == awssdk.StringValue(t.Key) {
return awssdk.StringValue(t.Value), nil
}
}
return nil, ErrTagNotFound
}
}
var extractStringPointerSliceValues = func(i interface{}) (interface{}, error) {
pointers, ok := i.([]*string)
if !ok {
return nil, fmt.Errorf("extract string pointer: not a string pointer slice but a %T", i)
}
return awssdk.StringValueSlice(pointers), nil
}
var extractStringSliceValues = func(key string) transformFn {
return func(i interface{}) (interface{}, error) {
var res []string
value := reflect.ValueOf(i)
if value.Kind() != reflect.Slice {
return nil, fmt.Errorf("extract slice: not a slice but a %T", i)
}
for i := 0; i < value.Len(); i++ {
e, err := extractFieldFn(key)(value.Index(i).Interface())
if err != nil {
return nil, err
}
str, ok := e.(string)
if !ok {
return nil, fmt.Errorf("extract string slice: not a string but a %T", e)
}
res = append(res, str)
}
return res, nil
}
}
var extractClassicLoadbListenerDescriptionsFn = func(i interface{}) (interface{}, error) {
listeners, ok := i.([]*elb.ListenerDescription)
if !ok {
return nil, fmt.Errorf("extract classic loadb listener descriptions: unexpected type %T", i)
}
var out []string
for _, d := range listeners {
if list := d.Listener; list != nil {
out = append(out, fmt.Sprintf("%s:%d:%s:%d", *list.Protocol, *list.LoadBalancerPort, *list.InstanceProtocol, *list.InstancePort))
}
}
return out, nil
}
var extractRoutesSliceFn = func(i interface{}) (interface{}, error) {
if _, ok := i.([]*ec2.Route); !ok {
return nil, fmt.Errorf("extract route: not a route slice but a %T", i)
}
var routes []*graph.Route
for _, r := range i.([]*ec2.Route) {
route := &graph.Route{}
var err error
if notEmpty(r.DestinationCidrBlock) {
if _, route.Destination, err = net.ParseCIDR(awssdk.StringValue(r.DestinationCidrBlock)); err != nil {
return nil, err
}
}
if notEmpty(r.DestinationIpv6CidrBlock) {
if _, route.DestinationIPv6, err = net.ParseCIDR(awssdk.StringValue(r.DestinationIpv6CidrBlock)); err != nil {
return nil, err
}
}
if notEmpty(r.DestinationPrefixListId) {
route.DestinationPrefixListId = awssdk.StringValue(r.DestinationPrefixListId)
}
if notEmpty(r.EgressOnlyInternetGatewayId) {
routeTarget := &graph.RouteTarget{Type: graph.EgressOnlyInternetGatewayTarget, Ref: awssdk.StringValue(r.EgressOnlyInternetGatewayId)}
route.Targets = append(route.Targets, routeTarget)
}
if notEmpty(r.GatewayId) {
routeTarget := &graph.RouteTarget{Type: graph.GatewayTarget, Ref: awssdk.StringValue(r.GatewayId)}
route.Targets = append(route.Targets, routeTarget)
}
if notEmpty(r.InstanceId) {
routeTarget := &graph.RouteTarget{Type: graph.InstanceTarget, Ref: awssdk.StringValue(r.InstanceId), Owner: awssdk.StringValue(r.InstanceOwnerId)}
route.Targets = append(route.Targets, routeTarget)
}
if notEmpty(r.NatGatewayId) {
routeTarget := &graph.RouteTarget{Type: graph.NatTarget, Ref: awssdk.StringValue(r.NatGatewayId)}
route.Targets = append(route.Targets, routeTarget)
}
if notEmpty(r.NetworkInterfaceId) {
routeTarget := &graph.RouteTarget{Type: graph.NetworkInterfaceTarget, Ref: awssdk.StringValue(r.NetworkInterfaceId)}
route.Targets = append(route.Targets, routeTarget)
}
if notEmpty(r.VpcPeeringConnectionId) {
routeTarget := &graph.RouteTarget{Type: graph.VpcPeeringConnectionTarget, Ref: awssdk.StringValue(r.VpcPeeringConnectionId)}
route.Targets = append(route.Targets, routeTarget)
}
routes = append(routes, route)
}
return routes, nil
}
var extractHasATrueBoolInStructSliceFn = func(key string) transformFn {
return func(i interface{}) (interface{}, error) {
var res bool
value := reflect.ValueOf(i)
if value.Kind() != reflect.Slice {
return nil, fmt.Errorf("extract true bool: not a slice but a %T", i)
}
for i := 0; i < value.Len(); i++ {
e, err := extractFieldFn(key)(value.Index(i).Interface())
if err != nil {
return res, err
}
if e == nil {
continue //Empty field
}
b, ok := e.(bool)
if !ok {
return nil, fmt.Errorf("extract true bool: the field %s is not a boolean, but has type: %T", key, e)
}
if b {
res = true
}
}
return res, nil
}
}
var extractDistributionOriginFn = func(i interface{}) (interface{}, error) {
if _, ok := i.(*cloudfront.Origins); !ok {
return nil, fmt.Errorf("extract origins: not a origins pointer but a %T", i)
}
var origins []*graph.DistributionOrigin
for _, o := range i.(*cloudfront.Origins).Items {
origin := &graph.DistributionOrigin{
ID: awssdk.StringValue(o.Id),
PublicDNS: awssdk.StringValue(o.DomainName),
PathPrefix: awssdk.StringValue(o.OriginPath),
}
if o.S3OriginConfig != nil && awssdk.StringValue(o.S3OriginConfig.OriginAccessIdentity) != "" {
origin.OriginType = "s3"
origin.Config = awssdk.StringValue(o.S3OriginConfig.OriginAccessIdentity)
}
origins = append(origins, origin)
}
return origins, nil
}
var extractStackOutputsFn = func(i interface{}) (interface{}, error) {
if _, ok := i.([]*cloudformation.Output); !ok {
return nil, fmt.Errorf("extract ouutputs not an output slice but a %T", i)
}
var keyVals []*graph.KeyValue
for _, out := range i.([]*cloudformation.Output) {
keyval := &graph.KeyValue{KeyName: awssdk.StringValue(out.OutputKey), Value: awssdk.StringValue(out.OutputValue)}
keyVals = append(keyVals, keyval)
}
return keyVals, nil
}
var extractStackParametersFn = func(i interface{}) (interface{}, error) {
if _, ok := i.([]*cloudformation.Parameter); !ok {
return nil, fmt.Errorf("extract parameters not a parameter slice but a %T", i)
}
var keyVals []*graph.KeyValue
for _, out := range i.([]*cloudformation.Parameter) {
keyval := &graph.KeyValue{KeyName: awssdk.StringValue(out.ParameterKey), Value: awssdk.StringValue(out.ParameterValue)}
keyVals = append(keyVals, keyval)
}
return keyVals, nil
}
var extractContainersImagesFn = func(i interface{}) (interface{}, error) {
if _, ok := i.([]*ecs.ContainerDefinition); !ok {
return nil, fmt.Errorf("extract containers images, not a container definition slice but a %T", i)
}
var keyVals []*graph.KeyValue
for _, out := range i.([]*ecs.ContainerDefinition) {
keyval := &graph.KeyValue{KeyName: awssdk.StringValue(out.Name), Value: awssdk.StringValue(out.Image)}
keyVals = append(keyVals, keyval)
}
return keyVals, nil
}
func extractDocumentDefaultVersion(i interface{}) (interface{}, error) {
if _, ok := i.([]*iam.PolicyVersion); !ok {
return nil, fmt.Errorf("extract default version of document, not a policy version slice but a %T", i)
}
for _, version := range i.([]*iam.PolicyVersion) {
if awssdk.BoolValue(version.IsDefaultVersion) {
docStr := awssdk.StringValue(version.Document)
if str, err := url.QueryUnescape(docStr); err == nil {
var buff bytes.Buffer
err = json.Compact(&buff, []byte(str))
return buff.String(), err
}
return docStr, nil
}
}
return "", nil
}
func extractURLEncodedJson(i interface{}) (interface{}, error) {
if _, ok := i.(*string); !ok {
return nil, fmt.Errorf("extract URL-encoded JSON, not a *string but a %T", i)
}
docStr := awssdk.StringValue(i.(*string))
if str, err := url.QueryUnescape(docStr); err == nil {
var buff bytes.Buffer
err = json.Compact(&buff, []byte(str))
return buff.String(), err
}
return docStr, nil
}
func notEmpty(str *string) bool {
return awssdk.StringValue(str) != ""
}
func HashFields(fields ...interface{}) string {
var buf bytes.Buffer
for _, field := range fields {
buf.WriteString(fmt.Sprint(field))
}
h := adler32.New()
buf.WriteTo(h)
return "awls-" + hex.EncodeToString(h.Sum(nil))
}