-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquery.go
212 lines (184 loc) · 4.69 KB
/
query.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
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/cloudwatch"
"sort"
"strconv"
"strings"
"time"
)
const debug int = 0
// Detail used to display last data
// in detail.html
type Detail struct {
Host string
Time string
Service string
Alert string
Value float64
Units string
}
// QueryResult populated after call to
// cloudwatch.GetMetricStatistics
type QueryResult struct {
// alert value for display
Alert string
// unit type eg Bytes, Count, etc
Units string
// query result value
Value float64
// Unix time converted to float64
Time float64
}
type MetricQuery struct {
// populated from thresh.json
Name string `json:"name"`
Host string `json:"hostname"`
Namespace string `json:"namespace"`
Dims []Dimension `json:"dimensions"`
Label string `json:"metric"`
Statistics string `json:"statistics"`
Warning string `json:"warning"`
Critical string `json:"critical"`
// results from aws query
Results []QueryResult
}
type Dimension struct {
DimName string `json:"dim_name"`
DimValue string `json:"dim_value"`
}
// getStatistics called after MetricQuery parameters are loaded with getThresholds
// returns with MetricQuery.Results poplulated with cloudwatch data
// will error if input values are incorrect or missing
func (mq *MetricQuery) getStatistics(timeframe string) error {
// convert timeframe into minutes
period := getPeriod(timeframe)
t := time.Now()
if mq.Namespace == "AWS/S3" {
timeframe = "-36h"
}
duration, _ := time.ParseDuration(timeframe)
s := t.Add(duration)
var dims []*cloudwatch.Dimension
// handle multiple dimensions
for i := 0; i < len(mq.Dims); i++ {
dims = append(dims, &cloudwatch.Dimension{
Name: aws.String(mq.Dims[i].DimName),
Value: aws.String(mq.Dims[i].DimValue),
})
}
// fill out GetMetricStatisticsInput for aws query
params := cloudwatch.GetMetricStatisticsInput{
EndTime: aws.Time(t),
Namespace: aws.String(mq.Namespace),
Period: aws.Int64(period),
StartTime: aws.Time(s),
Dimensions: dims,
MetricName: aws.String(mq.Label),
Statistics: []*string{
aws.String(mq.Statistics),
},
}
// aws cloudwatch call
resp, err := svc.GetMetricStatistics(¶ms)
if err != nil {
return fmt.Errorf("Metric query failed: %s", err.Error())
}
// handle no data returned from query
if len(resp.Datapoints) == 0 {
if debug == 1 {
fmt.Println("no datapoints")
}
data := QueryResult{
Value: 0.0,
Units: "Unknown",
Time: float64(time.Now().Unix()),
Alert: "info",
}
mq.Results = append(mq.Results, data)
return nil
}
// iterate through datapoints and append to MetricQuery.Results array
for _, dp := range resp.Datapoints {
unit := *dp.Unit
value := 0.0
switch mq.Statistics {
case "Maximum":
value = *dp.Maximum
case "Average":
value = *dp.Average
case "Sum":
value = *dp.Sum
case "SampleCount":
value = *dp.SampleCount
case "Minimum":
value = *dp.Minimum
}
data := QueryResult{
Value: value,
Units: unit,
Time: float64(dp.Timestamp.Unix()),
}
data.compareThresh(mq.Warning, mq.Critical)
mq.Results = append(mq.Results, data)
}
// sort data points by time
sort.Sort(ByTime(mq.Results))
if debug == 1 {
fmt.Printf("Get Statistics Result: %v", mq)
}
return nil
}
// function to compare threshold with query values and return html ready warning
func (qr *QueryResult) compareThresh(warn, crit string) {
// adjust for transform
value := qr.Value // make a copy
notopc := false
notopw := false
if qr.Units == "MB" {
value = value * 1048576.0
}
if qr.Units == "KB" {
value = value * 1024.0
}
var minwarn float64 = 0.0
var maxwarn float64 = 100.0
var mincrit float64 = 0.0
var maxcrit float64 = 100.0
warnings := strings.Split(warn, ":")
if warn[len(warn)-1] == ':' {
notopw = true
} else if len(warnings) < 2 {
minwarn = 0
maxwarn, _ = strconv.ParseFloat(warnings[0], 64)
} else {
minwarn, _ = strconv.ParseFloat(warnings[0], 64)
maxwarn, _ = strconv.ParseFloat(warnings[1], 64)
}
criticals := strings.Split(crit, ":")
if crit[len(crit)-1] == ':' {
notopc = true
} else if len(criticals) < 2 {
mincrit = 0.0
maxcrit, _ = strconv.ParseFloat(criticals[0], 64)
} else {
mincrit, _ = strconv.ParseFloat(criticals[0], 64)
maxcrit, _ = strconv.ParseFloat(criticals[1], 64)
}
// alerts for pretty twitter bootstrap colors
qr.Alert = "success"
if notopc {
if value < mincrit {
qr.Alert = "danger"
}
} else if value > maxcrit || value < mincrit {
qr.Alert = "danger"
} else if notopw {
if value < mincrit {
qr.Alert = "warning"
}
} else if value > maxwarn || value < minwarn {
qr.Alert = "warning"
}
}