-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmonitoring.go
435 lines (397 loc) · 14.3 KB
/
monitoring.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
package gokini
import (
"fmt"
"net/http"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"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/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
log "github.com/sirupsen/logrus"
)
// MonitoringConfiguration allows you to configure how record processing metrics are exposed
type MonitoringConfiguration struct {
MonitoringService string // Type of monitoring to expose. Supported types are "prometheus"
Prometheus prometheusMonitoringService
CloudWatch cloudWatchMonitoringService
service monitoringService
}
type monitoringService interface {
init() error
incrRecordsProcessed(string, int)
incrBytesProcessed(string, int64)
millisBehindLatest(string, float64)
leaseGained(string)
leaseLost(string)
leaseRenewed(string)
recordGetRecordsTime(string, float64)
recordProcessRecordsTime(string, float64)
}
func (m *MonitoringConfiguration) init(streamName string, workerID string, sess *session.Session) error {
if m.MonitoringService == "" {
m.service = &noopMonitoringService{}
return nil
}
switch m.MonitoringService {
case "prometheus":
m.Prometheus.KinesisStream = streamName
m.Prometheus.WorkerID = workerID
m.service = &m.Prometheus
case "cloudwatch":
m.CloudWatch.Session = sess
m.CloudWatch.KinesisStream = streamName
m.CloudWatch.WorkerID = workerID
m.service = &m.CloudWatch
default:
return fmt.Errorf("Invalid monitoring service type %s", m.MonitoringService)
}
return m.service.init()
}
type prometheusMonitoringService struct {
ListenAddress string
Namespace string
KinesisStream string
WorkerID string
processedRecords *prometheus.CounterVec
processedBytes *prometheus.CounterVec
behindLatestMillis *prometheus.GaugeVec
leasesHeld *prometheus.GaugeVec
leaseRenewals *prometheus.CounterVec
getRecordsTime *prometheus.HistogramVec
processRecordsTime *prometheus.HistogramVec
}
const defaultNamespace = "gokini"
func (p *prometheusMonitoringService) init() error {
if p.Namespace == "" {
p.Namespace = defaultNamespace
}
p.processedBytes = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: p.Namespace + `_processed_bytes`,
Help: "Number of bytes processed",
}, []string{"kinesisStream", "shard"})
p.processedRecords = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: p.Namespace + `_processed_records`,
Help: "Number of records processed",
}, []string{"kinesisStream", "shard"})
p.behindLatestMillis = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: p.Namespace + `_behind_latest_millis`,
Help: "The amount of milliseconds processing is behind",
}, []string{"kinesisStream", "shard"})
p.leasesHeld = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: p.Namespace + `_leases_held`,
Help: "The number of leases held by the worker",
}, []string{"kinesisStream", "shard", "workerID"})
p.leaseRenewals = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: p.Namespace + `_lease_renewals`,
Help: "The number of successful lease renewals",
}, []string{"kinesisStream", "shard", "workerID"})
p.getRecordsTime = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: p.Namespace + `_get_records_duration_milliseconds`,
Help: "The time taken to fetch records and process them",
}, []string{"kinesisStream", "shard"})
p.processRecordsTime = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: p.Namespace + `_process_records_duration_milliseconds`,
Help: "The time taken to process records",
}, []string{"kinesisStream", "shard"})
metrics := []prometheus.Collector{
p.processedBytes,
p.processedRecords,
p.behindLatestMillis,
p.leasesHeld,
p.leaseRenewals,
p.getRecordsTime,
p.processRecordsTime,
}
for _, metric := range metrics {
err := prometheus.Register(metric)
if err != nil {
return err
}
}
http.Handle("/metrics", promhttp.Handler())
go func() {
log.Debugf("Starting Prometheus listener on %s", p.ListenAddress)
err := http.ListenAndServe(p.ListenAddress, nil)
if err != nil {
log.Errorln("Error starting Prometheus metrics endpoint", err)
}
}()
return nil
}
func (p *prometheusMonitoringService) incrRecordsProcessed(shard string, count int) {
p.processedRecords.With(prometheus.Labels{"shard": shard, "kinesisStream": p.KinesisStream}).Add(float64(count))
}
func (p *prometheusMonitoringService) incrBytesProcessed(shard string, count int64) {
p.processedBytes.With(prometheus.Labels{"shard": shard, "kinesisStream": p.KinesisStream}).Add(float64(count))
}
func (p *prometheusMonitoringService) millisBehindLatest(shard string, millSeconds float64) {
p.behindLatestMillis.With(prometheus.Labels{"shard": shard, "kinesisStream": p.KinesisStream}).Set(millSeconds)
}
func (p *prometheusMonitoringService) leaseGained(shard string) {
p.leasesHeld.With(prometheus.Labels{"shard": shard, "kinesisStream": p.KinesisStream, "workerID": p.WorkerID}).Inc()
}
func (p *prometheusMonitoringService) leaseLost(shard string) {
p.leasesHeld.With(prometheus.Labels{"shard": shard, "kinesisStream": p.KinesisStream, "workerID": p.WorkerID}).Dec()
}
func (p *prometheusMonitoringService) leaseRenewed(shard string) {
p.leaseRenewals.With(prometheus.Labels{"shard": shard, "kinesisStream": p.KinesisStream, "workerID": p.WorkerID}).Inc()
}
func (p *prometheusMonitoringService) recordGetRecordsTime(shard string, time float64) {
p.getRecordsTime.With(prometheus.Labels{"shard": shard, "kinesisStream": p.KinesisStream}).Observe(time)
}
func (p *prometheusMonitoringService) recordProcessRecordsTime(shard string, time float64) {
p.processRecordsTime.With(prometheus.Labels{"shard": shard, "kinesisStream": p.KinesisStream}).Observe(time)
}
type noopMonitoringService struct{}
func (n *noopMonitoringService) init() error {
return nil
}
func (n *noopMonitoringService) incrRecordsProcessed(shard string, count int) {}
func (n *noopMonitoringService) incrBytesProcessed(shard string, count int64) {}
func (n *noopMonitoringService) millisBehindLatest(shard string, millSeconds float64) {}
func (n *noopMonitoringService) leaseGained(shard string) {}
func (n *noopMonitoringService) leaseLost(shard string) {}
func (n *noopMonitoringService) leaseRenewed(shard string) {}
func (n *noopMonitoringService) recordGetRecordsTime(shard string, time float64) {}
func (n *noopMonitoringService) recordProcessRecordsTime(shard string, time float64) {}
type cloudWatchMonitoringService struct {
Namespace string
KinesisStream string
WorkerID string
// What granularity we should send metrics to CW at. Note setting this to 1 will cost quite a bit of money
// At the time of writing (March 2018) about US$200 per month
ResolutionSec int
Session *session.Session
svc cloudwatchiface.CloudWatchAPI
shardMetrics map[string]*cloudWatchMetrics
}
type cloudWatchMetrics struct {
processedRecords int64
processedBytes int64
behindLatestMillis []float64
leasesHeld int64
leaseRenewals int64
getRecordsTime []float64
processRecordsTime []float64
sync.Mutex
}
func (cw *cloudWatchMonitoringService) init() error {
if cw.ResolutionSec == 0 {
cw.ResolutionSec = 60
}
cw.svc = cloudwatch.New(cw.Session)
cw.shardMetrics = make(map[string]*cloudWatchMetrics)
return nil
}
func (cw *cloudWatchMonitoringService) flushDaemon() {
previousFlushTime := time.Now()
resolutionDuration := time.Duration(cw.ResolutionSec) * time.Second
for {
time.Sleep(resolutionDuration - time.Now().Sub(previousFlushTime))
err := cw.flush()
if err != nil {
log.Errorln("Error sending metrics to CloudWatch", err)
}
previousFlushTime = time.Now()
}
}
func (cw *cloudWatchMonitoringService) flush() error {
for shard, metric := range cw.shardMetrics {
metric.Lock()
defaultDimensions := []*cloudwatch.Dimension{
&cloudwatch.Dimension{
Name: aws.String("shard"),
Value: &shard,
},
&cloudwatch.Dimension{
Name: aws.String("KinesisStreamName"),
Value: &cw.KinesisStream,
},
}
leaseDimensions := make([]*cloudwatch.Dimension, len(defaultDimensions))
copy(defaultDimensions, leaseDimensions)
leaseDimensions = append(leaseDimensions, &cloudwatch.Dimension{
Name: aws.String("WorkerID"),
Value: &cw.WorkerID,
})
metricTimestamp := time.Now()
_, err := cw.svc.PutMetricData(&cloudwatch.PutMetricDataInput{
Namespace: aws.String(cw.Namespace),
MetricData: []*cloudwatch.MetricDatum{
&cloudwatch.MetricDatum{
Dimensions: defaultDimensions,
MetricName: aws.String("RecordsProcessed"),
Unit: aws.String("Count"),
Timestamp: &metricTimestamp,
Value: aws.Float64(float64(metric.processedRecords)),
},
&cloudwatch.MetricDatum{
Dimensions: defaultDimensions,
MetricName: aws.String("DataBytesProcessed"),
Unit: aws.String("Byte"),
Timestamp: &metricTimestamp,
Value: aws.Float64(float64(metric.processedBytes)),
},
&cloudwatch.MetricDatum{
Dimensions: defaultDimensions,
MetricName: aws.String("MillisBehindLatest"),
Unit: aws.String("Milliseconds"),
Timestamp: &metricTimestamp,
StatisticValues: &cloudwatch.StatisticSet{
SampleCount: aws.Float64(float64(len(metric.behindLatestMillis))),
Sum: sumFloat64(metric.behindLatestMillis),
Maximum: maxFloat64(metric.behindLatestMillis),
Minimum: minFloat64(metric.behindLatestMillis),
},
},
&cloudwatch.MetricDatum{
Dimensions: defaultDimensions,
MetricName: aws.String("KinesisDataFetcher.getRecords.Time"),
Unit: aws.String("Milliseconds"),
Timestamp: &metricTimestamp,
StatisticValues: &cloudwatch.StatisticSet{
SampleCount: aws.Float64(float64(len(metric.getRecordsTime))),
Sum: sumFloat64(metric.getRecordsTime),
Maximum: maxFloat64(metric.getRecordsTime),
Minimum: minFloat64(metric.getRecordsTime),
},
},
&cloudwatch.MetricDatum{
Dimensions: defaultDimensions,
MetricName: aws.String("RecordProcessor.processRecords.Time"),
Unit: aws.String("Milliseconds"),
Timestamp: &metricTimestamp,
StatisticValues: &cloudwatch.StatisticSet{
SampleCount: aws.Float64(float64(len(metric.processRecordsTime))),
Sum: sumFloat64(metric.processRecordsTime),
Maximum: maxFloat64(metric.processRecordsTime),
Minimum: minFloat64(metric.processRecordsTime),
},
},
&cloudwatch.MetricDatum{
Dimensions: leaseDimensions,
MetricName: aws.String("RenewLease.Success"),
Unit: aws.String("Count"),
Timestamp: &metricTimestamp,
Value: aws.Float64(float64(metric.leaseRenewals)),
},
&cloudwatch.MetricDatum{
Dimensions: leaseDimensions,
MetricName: aws.String("CurrentLeases"),
Unit: aws.String("Count"),
Timestamp: &metricTimestamp,
Value: aws.Float64(float64(metric.leasesHeld)),
},
},
})
if err == nil {
metric.processedRecords = 0
metric.processedBytes = 0
metric.behindLatestMillis = []float64{}
metric.leaseRenewals = 0
metric.getRecordsTime = []float64{}
metric.processRecordsTime = []float64{}
}
metric.Unlock()
return err
}
return nil
}
func (cw *cloudWatchMonitoringService) incrRecordsProcessed(shard string, count int) {
if _, ok := cw.shardMetrics[shard]; !ok {
cw.shardMetrics[shard] = &cloudWatchMetrics{}
}
cw.shardMetrics[shard].Lock()
defer cw.shardMetrics[shard].Unlock()
cw.shardMetrics[shard].processedRecords += int64(count)
}
func (cw *cloudWatchMonitoringService) incrBytesProcessed(shard string, count int64) {
if _, ok := cw.shardMetrics[shard]; !ok {
cw.shardMetrics[shard] = &cloudWatchMetrics{}
}
cw.shardMetrics[shard].Lock()
defer cw.shardMetrics[shard].Unlock()
cw.shardMetrics[shard].processedBytes += count
}
func (cw *cloudWatchMonitoringService) millisBehindLatest(shard string, millSeconds float64) {
if _, ok := cw.shardMetrics[shard]; !ok {
cw.shardMetrics[shard] = &cloudWatchMetrics{}
}
cw.shardMetrics[shard].Lock()
defer cw.shardMetrics[shard].Unlock()
cw.shardMetrics[shard].behindLatestMillis = append(cw.shardMetrics[shard].behindLatestMillis, millSeconds)
}
func (cw *cloudWatchMonitoringService) leaseGained(shard string) {
if _, ok := cw.shardMetrics[shard]; !ok {
cw.shardMetrics[shard] = &cloudWatchMetrics{}
}
cw.shardMetrics[shard].Lock()
defer cw.shardMetrics[shard].Unlock()
cw.shardMetrics[shard].leasesHeld++
}
func (cw *cloudWatchMonitoringService) leaseLost(shard string) {
if _, ok := cw.shardMetrics[shard]; !ok {
cw.shardMetrics[shard] = &cloudWatchMetrics{}
}
cw.shardMetrics[shard].Lock()
defer cw.shardMetrics[shard].Unlock()
cw.shardMetrics[shard].leasesHeld--
}
func (cw *cloudWatchMonitoringService) leaseRenewed(shard string) {
if _, ok := cw.shardMetrics[shard]; !ok {
cw.shardMetrics[shard] = &cloudWatchMetrics{}
}
cw.shardMetrics[shard].Lock()
defer cw.shardMetrics[shard].Unlock()
cw.shardMetrics[shard].leaseRenewals++
}
func (cw *cloudWatchMonitoringService) recordGetRecordsTime(shard string, time float64) {
if _, ok := cw.shardMetrics[shard]; !ok {
cw.shardMetrics[shard] = &cloudWatchMetrics{}
}
cw.shardMetrics[shard].Lock()
defer cw.shardMetrics[shard].Unlock()
cw.shardMetrics[shard].getRecordsTime = append(cw.shardMetrics[shard].getRecordsTime, time)
}
func (cw *cloudWatchMonitoringService) recordProcessRecordsTime(shard string, time float64) {
if _, ok := cw.shardMetrics[shard]; !ok {
cw.shardMetrics[shard] = &cloudWatchMetrics{}
}
cw.shardMetrics[shard].Lock()
defer cw.shardMetrics[shard].Unlock()
cw.shardMetrics[shard].processRecordsTime = append(cw.shardMetrics[shard].processRecordsTime, time)
}
func sumFloat64(slice []float64) *float64 {
sum := float64(0)
for _, num := range slice {
sum += num
}
return &sum
}
func maxFloat64(slice []float64) *float64 {
if len(slice) < 1 {
return aws.Float64(0)
}
max := slice[0]
for _, num := range slice {
if num > max {
max = num
}
}
return &max
}
func minFloat64(slice []float64) *float64 {
if len(slice) < 1 {
return aws.Float64(0)
}
min := slice[0]
for _, num := range slice {
if num < min {
min = num
}
}
return &min
}