forked from mozilla-services/heka-mozsvc-plugins
/
cloudwatch.go
400 lines (368 loc) · 10.6 KB
/
cloudwatch.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
/***** BEGIN LICENSE BLOCK *****
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# The Initial Developer of the Original Code is the Mozilla Foundation.
# Portions created by the Initial Developer are Copyright (C) 2012
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Ben Bangert (bbangert@mozilla.com)
#
# ***** END LICENSE BLOCK *****/
package heka_mozsvc_plugins
import (
"code.google.com/p/go-uuid/uuid"
"encoding/json"
"errors"
"fmt"
"github.com/crowdmob/goamz/aws"
"github.com/crowdmob/goamz/cloudwatch"
"github.com/feyeleanor/sets"
"github.com/mozilla-services/heka/message"
"github.com/mozilla-services/heka/pipeline"
"log"
"time"
)
var validMetricStatistics = sets.SSet(
"Average",
"Sum",
"SampleCount",
"Maximum",
"Minimum",
)
var validUnits = sets.SSet(
"Seconds",
"Microseconds",
"Milliseconds",
"Bytes",
"Kilobytes",
"Megabytes",
"Gigabytes",
"Terabytes",
"Bits",
"Kilobits",
"Megabits",
"Gigabits",
"Terabits",
"Percent",
"Count",
"Bytes/Second",
"Kilobytes/Second",
"Megabytes/Second",
"Gigabytes/Second",
"Terabytes/Second",
"Bits/Second",
"Kilobits/Second",
"Megabits/Second",
"Gigabits/Second",
"Terabits/Second",
"Count/Second",
)
// Cloudwatch Input Config
type CloudwatchInputConfig struct {
// AWS Secret Key
SecretKey string `toml:"secret_key"`
// AWS Access Key
AccessKey string `toml:"access_key"`
// AWS Region, ie. us-west-1, eu-west-1
Region string
// Cloudwatch Namespace, ie. AWS/Billing, AWS/DynamoDB, custom...
Namespace string
// List of dimensions to query
Dimensions map[string]string
// Metric name
MetricName string `toml:"metric_name"`
// Unit
Unit string
// Period for data points, must be factor of 60
Period int
// Polling period, how often as a duration to poll for new
// metrics. The first poll on startup will not be done until this
// period is reached.
PollInterval string `toml:"poll_interval"`
// What statistic values to retrieve for the metrics, valid values
// are Average, Sum, SampleCount, Maximum, Minumum
Statistics []string
}
// Cloudwatch Output Config
type CloudwatchOutputConfig struct {
// AWS Secret Key
SecretKey string `toml:"secret_key"`
// AWS Access Key
AccessKey string `toml:"access_key"`
// AWS Region, ie. us-west-1, eu-west-1
Region string
// Cloudwatch Namespace, ie. AWS/Billing, AWS/DynamoDB, custom...
Namespace string
// How many retries to attempt if AWS is not responding, increases
// exponentially until retries are met for a message
Retries int
// Metric backlog, how many messages to buffer sending
Backlog int
// Time zone in which the timestamps in the text are presumed to be in.
// Should be a location name corresponding to a file in the IANA Time Zone
// database (e.g. "America/Los_Angeles"), as parsed by Go's
// `time.LoadLocation()` function (see
// http://golang.org/pkg/time/#LoadLocation). Defaults to "UTC". Not
// required if valid time zone info is in the timestamp itself.
TimestampLocation string `toml:"timestamp_location"`
}
type CloudwatchInput struct {
cw *cloudwatch.CloudWatch
req *cloudwatch.GetMetricStatisticsRequest
pollInterval time.Duration
namespace string
stopChan chan bool
}
func (cwi *CloudwatchInput) ConfigStruct() interface{} {
return &CloudwatchInputConfig{Period: 60}
}
func (cwi *CloudwatchInput) Init(config interface{}) (err error) {
conf := config.(*CloudwatchInputConfig)
statisticsSet := sets.SSet(conf.Statistics...)
switch {
case conf.MetricName == "":
err = errors.New("No metric name supplied")
case conf.Period < 60 || conf.Period%60 != 0:
err = errors.New("Period must be divisible by 60")
case len(conf.Statistics) < 1:
err = errors.New("text·2")
case conf.Unit != "" && !validUnits.Member(conf.Unit):
err = errors.New("Unit is not a valid value")
case len(conf.Statistics) < 1:
err = errors.New("No statistics supplied")
case validMetricStatistics.Union(statisticsSet).Len() != validMetricStatistics.Len():
err = errors.New("Invalid statistic values supplied")
}
if err != nil {
return
}
dims := make([]cloudwatch.Dimension, 0)
for k, v := range conf.Dimensions {
dims = append(dims, cloudwatch.Dimension{k, v})
}
auth := aws.Auth{AccessKey: conf.AccessKey, SecretKey: conf.SecretKey}
cwi.req = &cloudwatch.GetMetricStatisticsRequest{
MetricName: conf.MetricName,
Period: conf.Period,
Unit: conf.Unit,
Statistics: conf.Statistics,
Dimensions: dims,
}
cwi.pollInterval, err = time.ParseDuration(conf.PollInterval)
if err != nil {
return
}
region, ok := aws.Regions[conf.Region]
if !ok {
err = errors.New("Region of that name not found.")
return
}
cwi.namespace = conf.Namespace
cwi.cw, err = cloudwatch.NewCloudWatch(auth, region.CloudWatchServicepoint,
conf.Namespace)
return
}
func newField(pack *pipeline.PipelinePack, name string, value interface{}) {
var field *message.Field
var err error
if field, err = message.NewField(name, value, ""); err == nil {
pack.Message.AddField(field)
} else {
log.Println("CloudwatchInput can't add field: ", name)
}
}
func (cwi *CloudwatchInput) Run(ir pipeline.InputRunner, h pipeline.PluginHelper) (err error) {
cwi.stopChan = make(chan bool)
cwi.req.StartTime = time.Now()
ticker := time.NewTicker(cwi.pollInterval)
ok := true
var (
resp *cloudwatch.GetMetricStatisticsResponse
point cloudwatch.Datapoint
pack *pipeline.PipelinePack
dim cloudwatch.Dimension
)
metricLoop:
for ok {
select {
case _, ok = <-cwi.stopChan:
continue
case <-ticker.C:
cwi.req.EndTime = time.Now()
resp, err = cwi.cw.GetMetricStatistics(cwi.req)
if err != nil {
ir.LogError(err)
err = nil
continue
}
for _, point = range resp.GetMetricStatisticsResult.Datapoints {
pack, ok = <-ir.InChan()
if !ok {
break metricLoop
}
pack.Message.SetType("cloudwatch")
for _, dim = range cwi.req.Dimensions {
newField(pack, "Dimension."+dim.Name, dim.Value)
}
newField(pack, "Period", cwi.req.Period)
newField(pack, "Average", point.Average)
newField(pack, "Maximum", point.Maximum)
newField(pack, "Minimum", point.Minimum)
newField(pack, "SampleCount", point.SampleCount)
newField(pack, "Unit", point.Unit)
newField(pack, "Sum", point.Sum)
pack.Message.SetUuid(uuid.NewRandom())
pack.Message.SetTimestamp(point.Timestamp.UTC().UnixNano())
pack.Message.SetLogger(cwi.namespace)
pack.Message.SetPayload(cwi.req.MetricName)
ir.Inject(pack)
}
cwi.req.StartTime = cwi.req.EndTime.Add(time.Duration(1) * time.Nanosecond)
}
}
return nil
}
func (cwi *CloudwatchInput) Stop() {
close(cwi.stopChan)
}
type JsonDatum struct {
Dimensions []cloudwatch.Dimension
MetricName string
StatisticValues []cloudwatch.StatisticSet
Timestamp string
Unit string
Value float64
}
type CloudwatchDatapointPayload struct {
Datapoints []JsonDatum
}
type CloudwatchDatapoints struct {
Datapoints []cloudwatch.MetricDatum
}
type CloudwatchOutput struct {
cw *cloudwatch.CloudWatch
retries int
backlog int
stopChan chan bool
tzLocation *time.Location
}
func (cwo *CloudwatchOutput) ConfigStruct() interface{} {
return &CloudwatchOutputConfig{Retries: 3, Backlog: 10}
}
func (cwo *CloudwatchOutput) Init(config interface{}) (err error) {
conf := config.(*CloudwatchOutputConfig)
auth := aws.Auth{AccessKey: conf.AccessKey, SecretKey: conf.SecretKey}
cwo.stopChan = make(chan bool)
region, ok := aws.Regions[conf.Region]
if !ok {
err = errors.New("Region of that name not found.")
return
}
cwo.backlog = conf.Backlog
cwo.retries = conf.Retries
if cwo.cw, err = cloudwatch.NewCloudWatch(auth, region.CloudWatchServicepoint,
conf.Namespace); err != nil {
return
}
if cwo.tzLocation, err = time.LoadLocation(conf.TimestampLocation); err != nil {
err = fmt.Errorf("CloudwatchOutput unknown timestamp_location '%s': %s",
conf.TimestampLocation, err)
}
return
}
func (cwo *CloudwatchOutput) Run(or pipeline.OutputRunner, h pipeline.PluginHelper) (err error) {
inChan := or.InChan()
payloads := make(chan CloudwatchDatapoints, cwo.backlog)
go cwo.Submitter(payloads, or)
var (
pack *pipeline.PipelinePack
msg *message.Message
rawDataPoints *CloudwatchDatapointPayload
dataPoints *CloudwatchDatapoints
)
dataPoints = new(CloudwatchDatapoints)
dataPoints.Datapoints = make([]cloudwatch.MetricDatum, 0, 0)
for pack = range inChan {
rawDataPoints = new(CloudwatchDatapointPayload)
msg = pack.Message
err = json.Unmarshal([]byte(msg.GetPayload()), rawDataPoints)
if err != nil {
or.LogMessage(fmt.Sprintf("warning, unable to parse payload: %s", err))
err = nil
continue
}
// Run through the list and convert them to CloudwatchDatapoints
for _, rawDatum := range rawDataPoints.Datapoints {
datum := cloudwatch.MetricDatum{
Dimensions: rawDatum.Dimensions,
MetricName: rawDatum.MetricName,
Unit: rawDatum.Unit,
Value: rawDatum.Value,
StatisticValues: rawDatum.StatisticValues,
}
if rawDatum.Timestamp != "" {
parsedTime, err := message.ForgivingTimeParse("", rawDatum.Timestamp, cwo.tzLocation)
if err != nil {
or.LogMessage(fmt.Sprintf("unable to parse timestamp for datum: %s", rawDatum))
continue
}
datum.Timestamp = parsedTime
}
dataPoints.Datapoints = append(dataPoints.Datapoints, datum)
}
payloads <- *dataPoints
dataPoints.Datapoints = dataPoints.Datapoints[:0]
rawDataPoints.Datapoints = rawDataPoints.Datapoints[:0]
pack.Recycle()
}
or.LogMessage("shutting down AWS Cloudwatch submitter")
cwo.stopChan <- true
<-cwo.stopChan
return
}
func (cwo *CloudwatchOutput) Submitter(payloads chan CloudwatchDatapoints,
or pipeline.OutputRunner) {
var (
payload CloudwatchDatapoints
curTry int
backOff time.Duration = time.Duration(10) * time.Millisecond
err error
stopping bool
)
curDuration := backOff
for !stopping {
select {
case stopping = <-cwo.stopChan:
continue
case payload = <-payloads:
for curTry < cwo.retries {
_, err = cwo.cw.PutMetricData(payload.Datapoints)
if err != nil {
curTry += 1
time.Sleep(curDuration)
curDuration *= 2
} else {
break
}
}
curDuration = backOff
curTry = 0
if err != nil {
or.LogError(err)
err = nil
}
}
}
close(cwo.stopChan)
}
func init() {
pipeline.RegisterPlugin("CloudwatchInput", func() interface{} {
return new(CloudwatchInput)
})
pipeline.RegisterPlugin("CloudwatchOutput", func() interface{} {
return new(CloudwatchOutput)
})
}