/
cloudwatchmetricbeat.go
250 lines (203 loc) · 6.07 KB
/
cloudwatchmetricbeat.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
package beater
import (
"errors"
"fmt"
"time"
"github.com/elastic/beats/libbeat/beat"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/logp"
"github.com/elastic/beats/libbeat/publisher"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatch"
"github.com/aws/aws-sdk-go/service/cloudwatch/cloudwatchiface"
"github.com/narmitech/cloudwatchmetricbeat/config"
)
type Cloudwatchmetricbeat struct {
done chan struct{}
config config.Config
client publisher.Client
// Client to amazon cloudwatch API
awsClient cloudwatchiface.CloudWatchAPI
// AWS client session
session *session.Session
}
// Creates beater
func New(b *beat.Beat, cfg *common.Config) (beat.Beater, error) {
config := config.DefaultConfig
if err := cfg.Unpack(&config); err != nil {
return nil, fmt.Errorf("Error reading config file: %v", err)
}
logp.Info(
"settings: " +
fmt.Sprintf("config=%+v", config),
)
sess := session.Must(session.NewSession(&aws.Config{
Retryer: client.DefaultRetryer{NumMaxRetries: 10},
Region: aws.String(config.AWSRegion),
}))
// Create cloudwatch session
svc := cloudwatch.New(sess)
beat := &Cloudwatchmetricbeat{
done: make(chan struct{}),
config: config,
session: sess,
awsClient: svc,
}
return beat, nil
}
func (cwb *Cloudwatchmetricbeat) Run(b *beat.Beat) error {
logp.Info("cloudwatchmetricbeat is running! Hit CTRL-C to stop it.")
cwb.client = b.Publisher.Connect()
if cwb.config.Period > 0 {
go cwb.monitor()
<-cwb.done
} else {
logp.Info("Period is zero, running once and exiting.")
cwb.refreshMetrics()
for range cwb.config.Prospectors {
<-cwb.done
}
}
return nil
}
func (b *Cloudwatchmetricbeat) Stop() {
b.client.Close()
close(b.done)
}
func (b *Cloudwatchmetricbeat) monitor() {
ticker := time.NewTicker(b.config.Period)
defer ticker.Stop()
for {
select {
case <-ticker.C:
b.refreshMetrics()
}
}
}
func (b *Cloudwatchmetricbeat) refreshMetrics() {
for _, configProspector := range b.config.Prospectors {
p := NewProspector(b, configProspector)
go func() {
p.Monitor()
if b.config.Period <= 0 {
b.done <- struct{}{} // signal we're done
}
}()
}
}
// manager
const DefaultPeriodSeconds = 60
const DefaultDelaySeconds = 300
const DefaultRangeSeconds = 600
const DefaultAwsStatistic = "Average"
type Prospector struct {
config config.Prospector
beat *Cloudwatchmetricbeat
}
func NewProspector(beat *Cloudwatchmetricbeat, c config.Prospector) *Prospector {
return &Prospector{
config: c,
beat: beat,
}
}
func (p *Prospector) Monitor() {
for m := range p.config.Metrics {
metric := &p.config.Metrics[m]
// validate metric
if metric.PeriodSeconds == 0 {
metric.PeriodSeconds = DefaultPeriodSeconds
}
if metric.DelaySeconds == 0 {
metric.DelaySeconds = DefaultDelaySeconds
}
if metric.RangeSeconds == 0 {
metric.RangeSeconds = DefaultRangeSeconds
}
if len(metric.AWSStatistics) == 0 {
metric.AWSStatistics = []string{DefaultAwsStatistic}
}
event, err := p.fetchMetric(metric)
if err == nil {
opts := []publisher.ClientOption{}
if p.beat.config.Period <= 0 {
opts = []publisher.ClientOption{publisher.Sync}
}
p.beat.client.PublishEvent(*event, opts...)
}
}
}
func (p *Prospector) fetchMetric(metric *config.Metric) (*common.MapStr, error) {
now := time.Now()
end := now.Add(time.Duration(-metric.DelaySeconds) * time.Second)
params := &cloudwatch.GetMetricStatisticsInput{
EndTime: aws.Time(end),
StartTime: aws.Time(end.Add(time.Duration(-metric.RangeSeconds) * time.Second)),
Period: aws.Int64(int64(metric.PeriodSeconds)),
MetricName: aws.String(metric.AWSMetricName),
Namespace: aws.String(metric.AWSNamespace),
Dimensions: []*cloudwatch.Dimension{},
Statistics: []*string{},
Unit: nil,
}
for _, stat := range metric.AWSStatistics {
params.Statistics = append(params.Statistics, aws.String(stat))
}
// Loop through the dimensions selects to build the filters
for dim := range metric.AWSDimensionSelect {
for val := range metric.AWSDimensionSelect[dim] {
dimValue := metric.AWSDimensionSelect[dim][val]
params.Dimensions = append(params.Dimensions, &cloudwatch.Dimension{
Name: aws.String(dim),
Value: aws.String(dimValue),
})
}
}
// Call CloudWatch to gather the datapoints
resp, err := p.beat.awsClient.GetMetricStatistics(params)
logp.Info("making request: " + fmt.Sprintf("params=%+v", params))
if err != nil {
logp.Err("aws client error: ", err)
return nil, err
}
// There's nothing in there, don't publish the metric
if len(resp.Datapoints) == 0 {
return nil, errors.New("successful call to cloudwatch, but no data")
}
// Pick the latest datapoint
dp := getLatestDatapoint(resp.Datapoints)
event := common.MapStr{
"@timestamp": common.Time(*dp.Timestamp),
"type": "cloudwatchset",
"cloudwatchset.name": p.config.Id,
"cloudwatchset.resource_id_type": toSnake(*params.Dimensions[0].Name), // TODO handle multiple dimensions
"cloudwatchset.resource_id": params.Dimensions[0].Value,
"cloudwatchset.namespace": metric.AWSNamespace,
}
if dp.Sum != nil {
event[fmt.Sprintf("%s.sum", toSnake(metric.AWSMetricName))] = float64(*dp.Sum)
}
if dp.Average != nil {
event[fmt.Sprintf("%s.avg", toSnake(metric.AWSMetricName))] = float64(*dp.Average)
}
if dp.Maximum != nil {
event[fmt.Sprintf("%s.max", toSnake(metric.AWSMetricName))] = float64(*dp.Maximum)
}
if dp.Minimum != nil {
event[fmt.Sprintf("%s.min", toSnake(metric.AWSMetricName))] = float64(*dp.Minimum)
}
if dp.SampleCount != nil {
event[fmt.Sprintf("%s.count", toSnake(metric.AWSMetricName))] = float64(*dp.SampleCount)
}
return &event, nil
}
func getLatestDatapoint(datapoints []*cloudwatch.Datapoint) *cloudwatch.Datapoint {
var latest *cloudwatch.Datapoint = nil
for dp := range datapoints {
if latest == nil || latest.Timestamp.Before(*datapoints[dp].Timestamp) {
latest = datapoints[dp]
}
}
return latest
}