-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
aws.go
222 lines (196 loc) · 6.83 KB
/
aws.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
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License;
// you may not use this file except in compliance with the Elastic License.
package aws
import (
"context"
"time"
awssdk "github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/ec2"
"github.com/aws/aws-sdk-go-v2/service/ec2/ec2iface"
"github.com/aws/aws-sdk-go-v2/service/iam"
"github.com/aws/aws-sdk-go-v2/service/rds"
"github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi"
"github.com/aws/aws-sdk-go-v2/service/sts"
"github.com/pkg/errors"
"github.com/elastic/beats/v7/libbeat/common"
"github.com/elastic/beats/v7/metricbeat/mb"
awscommon "github.com/elastic/beats/v7/x-pack/libbeat/common/aws"
)
// Config defines all required and optional parameters for aws metricsets
type Config struct {
Period time.Duration `config:"period" validate:"nonzero,required"`
Regions []string `config:"regions"`
AWSConfig awscommon.ConfigAWS `config:",inline"`
TagsFilter []Tag `config:"tags_filter"`
}
// MetricSet is the base metricset for all aws metricsets
type MetricSet struct {
mb.BaseMetricSet
RegionsList []string
Endpoint string
Period time.Duration
AwsConfig *awssdk.Config
AccountName string
AccountID string
TagsFilter []Tag
}
// Tag holds a configuration specific for ec2 and cloudwatch metricset.
type Tag struct {
Key string `config:"key"`
Value string `config:"value"`
}
// ModuleName is the name of this module.
const ModuleName = "aws"
func init() {
if err := mb.Registry.AddModule(ModuleName, newModule); err != nil {
panic(err)
}
}
func newModule(base mb.BaseModule) (mb.Module, error) {
var config Config
if err := base.UnpackConfig(&config); err != nil {
return nil, err
}
return &base, nil
}
// NewMetricSet creates a base metricset for aws metricsets
func NewMetricSet(base mb.BaseMetricSet) (*MetricSet, error) {
var config Config
err := base.Module().UnpackConfig(&config)
if err != nil {
return nil, err
}
awsConfig, err := awscommon.GetAWSCredentials(config.AWSConfig)
if err != nil {
return nil, errors.Wrap(err, "failed to get aws credentials, please check AWS credential in config")
}
_, err = awsConfig.Credentials.Retrieve()
if err != nil {
return nil, errors.Wrap(err, "failed to retrieve aws credentials, please check AWS credential in config")
}
metricSet := MetricSet{
BaseMetricSet: base,
Period: config.Period,
AwsConfig: &awsConfig,
TagsFilter: config.TagsFilter,
}
base.Logger().Debug("Metricset level config for period: ", metricSet.Period)
base.Logger().Debug("Metricset level config for tags filter: ", metricSet.TagsFilter)
// Get IAM account name
awsConfig.Region = "us-east-1"
svcIam := iam.New(awscommon.EnrichAWSConfigWithEndpoint(
config.AWSConfig.Endpoint, "iam", "", awsConfig))
req := svcIam.ListAccountAliasesRequest(&iam.ListAccountAliasesInput{})
output, err := req.Send(context.TODO())
if err != nil {
base.Logger().Warn("failed to list account aliases, please check permission setting: ", err)
} else {
// There can be more than one aliases for each account, for now we are only
// collecting the first one.
if output.AccountAliases != nil {
metricSet.AccountName = output.AccountAliases[0]
base.Logger().Debug("AWS Credentials belong to account name: ", metricSet.AccountName)
}
}
// Get IAM account id
svcSts := sts.New(awscommon.EnrichAWSConfigWithEndpoint(
config.AWSConfig.Endpoint, "sts", "", awsConfig))
reqIdentity := svcSts.GetCallerIdentityRequest(&sts.GetCallerIdentityInput{})
outputIdentity, err := reqIdentity.Send(context.TODO())
if err != nil {
base.Logger().Warn("failed to get caller identity, please check permission setting: ", err)
} else {
metricSet.AccountID = *outputIdentity.Account
base.Logger().Debug("AWS Credentials belong to account ID: ", metricSet.AccountID)
}
// Construct MetricSet with a full regions list
if config.Regions == nil {
svcEC2 := ec2.New(awscommon.EnrichAWSConfigWithEndpoint(
config.AWSConfig.Endpoint, "ec2", "", awsConfig))
completeRegionsList, err := getRegions(svcEC2)
if err != nil {
return nil, err
}
metricSet.RegionsList = completeRegionsList
base.Logger().Debug("Metricset level config for regions: ", metricSet.RegionsList)
return &metricSet, nil
}
// Construct MetricSet with specific regions list from config
metricSet.RegionsList = config.Regions
base.Logger().Debug("Metricset level config for regions: ", metricSet.RegionsList)
return &metricSet, nil
}
func getRegions(svc ec2iface.ClientAPI) (completeRegionsList []string, err error) {
input := &ec2.DescribeRegionsInput{}
req := svc.DescribeRegionsRequest(input)
output, err := req.Send(context.TODO())
if err != nil {
err = errors.Wrap(err, "Failed DescribeRegions")
return
}
for _, region := range output.Regions {
completeRegionsList = append(completeRegionsList, *region.RegionName)
}
return
}
// StringInSlice checks if a string is already exists in list and its location
func StringInSlice(str string, list []string) (bool, int) {
for idx, v := range list {
if v == str {
return true, idx
}
}
// If this string doesn't exist in given list, then return location to be -1
return false, -1
}
// InitEvent initialize mb.Event with basic information like service.name, cloud.provider
func InitEvent(regionName string, accountName string, accountID string) mb.Event {
event := mb.Event{}
event.MetricSetFields = common.MapStr{}
event.ModuleFields = common.MapStr{}
event.RootFields = common.MapStr{}
event.RootFields.Put("cloud.provider", "aws")
if regionName != "" {
event.RootFields.Put("cloud.region", regionName)
}
if accountName != "" {
event.RootFields.Put("cloud.account.name", accountName)
}
if accountID != "" {
event.RootFields.Put("cloud.account.id", accountID)
}
return event
}
// CheckTagFiltersExist compare tags filter with a set of tags to see if tags
// filter is a subset of tags
func CheckTagFiltersExist(tagsFilter []Tag, tags interface{}) bool {
var tagKeys []string
var tagValues []string
switch tags.(type) {
case []resourcegroupstaggingapi.Tag:
tagsResource := tags.([]resourcegroupstaggingapi.Tag)
for _, tag := range tagsResource {
tagKeys = append(tagKeys, *tag.Key)
tagValues = append(tagValues, *tag.Value)
}
case []ec2.Tag:
tagsEC2 := tags.([]ec2.Tag)
for _, tag := range tagsEC2 {
tagKeys = append(tagKeys, *tag.Key)
tagValues = append(tagValues, *tag.Value)
}
case []rds.Tag:
tagsRDS := tags.([]rds.Tag)
for _, tag := range tagsRDS {
tagKeys = append(tagKeys, *tag.Key)
tagValues = append(tagValues, *tag.Value)
}
}
for _, tagFilter := range tagsFilter {
if exists, idx := StringInSlice(tagFilter.Key, tagKeys); !exists || tagValues[idx] != tagFilter.Value {
return false
}
}
return true
}