/
chart.go
310 lines (303 loc) · 7.7 KB
/
chart.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
package web
import (
"encoding/base64"
"encoding/json"
"fmt"
"image/color"
"net/http"
"strconv"
"strings"
"time"
"bosun.org/cmd/bosun/expr"
"bosun.org/cmd/bosun/sched"
"bosun.org/metadata"
"bosun.org/models"
"bosun.org/opentsdb"
"github.com/MiniProfiler/go/miniprofiler"
svg "github.com/ajstarks/svgo"
"github.com/bosun-monitor/annotate"
"github.com/bradfitz/slice"
"github.com/gorilla/mux"
"github.com/vdobler/chart"
"github.com/vdobler/chart/svgg"
)
// Graph takes an OpenTSDB request data structure and queries OpenTSDB. Use the
// json parameter to pass JSON. Use the b64 parameter to pass base64-encoded
// JSON.
func Graph(t miniprofiler.Timer, w http.ResponseWriter, r *http.Request) (interface{}, error) {
j := []byte(r.FormValue("json"))
if bs := r.FormValue("b64"); bs != "" {
b, err := base64.StdEncoding.DecodeString(bs)
if err != nil {
return nil, err
}
j = b
}
if len(j) == 0 {
return nil, fmt.Errorf("either json or b64 required")
}
oreq, err := opentsdb.RequestFromJSON(j)
if err != nil {
return nil, err
}
if ads_v := r.FormValue("autods"); ads_v != "" {
ads_i, err := strconv.Atoi(ads_v)
if err != nil {
return nil, err
}
if err := oreq.AutoDownsample(ads_i); err != nil {
return nil, err
}
}
ar := make(map[int]bool)
for _, v := range r.Form["autorate"] {
if i, err := strconv.Atoi(v); err == nil {
ar[i] = true
}
}
queries := make([]string, len(oreq.Queries))
var start, end string
var startT, endT time.Time
if s, ok := oreq.Start.(string); ok && strings.Contains(s, "-ago") {
startT, err = opentsdb.ParseTime(s)
if err != nil {
return nil, err
}
start = strings.TrimSuffix(s, "-ago")
}
if s, ok := oreq.End.(string); ok && strings.Contains(s, "-ago") {
endT, err = opentsdb.ParseTime(s)
if err != nil {
return nil, err
}
end = strings.TrimSuffix(s, "-ago")
}
if start == "" && end == "" {
s, sok := oreq.Start.(int64)
e, eok := oreq.End.(int64)
if sok && eok {
start = fmt.Sprintf("%vs", e-s)
startT = time.Unix(s, 0)
endT = time.Unix(e, 0)
if err != nil {
return nil, err
}
}
}
if endT.Equal(time.Time{}) {
endT = time.Now().UTC()
}
m_units := make(map[string]string)
for i, q := range oreq.Queries {
if ar[i] {
meta, err := schedule.MetadataMetrics(q.Metric)
if err != nil {
return nil, err
}
if meta == nil {
return nil, fmt.Errorf("no metadata for %s: cannot use auto rate", q)
}
if meta.Unit != "" {
m_units[q.Metric] = meta.Unit
}
if meta.Rate != "" {
switch meta.Rate {
case metadata.Gauge:
// ignore
case metadata.Rate:
q.Rate = true
case metadata.Counter:
q.Rate = true
q.RateOptions = opentsdb.RateOptions{
Counter: true,
ResetValue: 1,
}
default:
return nil, fmt.Errorf("unknown metadata rate: %s", meta.Rate)
}
}
}
queries[i] = fmt.Sprintf(`q("%v", "%v", "%v")`, q, start, end)
if !schedule.SystemConf.GetTSDBContext().Version().FilterSupport() {
if err := schedule.Search.Expand(q); err != nil {
return nil, err
}
}
}
var tr opentsdb.ResponseSet
b, _ := json.MarshalIndent(oreq, "", " ")
t.StepCustomTiming("tsdb", "query", string(b), func() {
h := schedule.SystemConf.GetTSDBHost()
if h == "" {
err = fmt.Errorf("tsdbHost not set")
return
}
tr, err = oreq.Query(h)
})
if err != nil {
return nil, err
}
cs, err := makeChart(tr, m_units)
if err != nil {
return nil, err
}
if _, present := r.Form["png"]; present {
c := chart.ScatterChart{
Title: fmt.Sprintf("%v - %v", oreq.Start, queries),
}
c.XRange.Time = true
if min, err := strconv.ParseFloat(r.FormValue("min"), 64); err == nil {
c.YRange.MinMode.Fixed = true
c.YRange.MinMode.Value = min
}
if max, err := strconv.ParseFloat(r.FormValue("max"), 64); err == nil {
c.YRange.MaxMode.Fixed = true
c.YRange.MaxMode.Value = max
}
for ri, r := range cs {
pts := make([]chart.EPoint, len(r.Data))
for idx, v := range r.Data {
pts[idx].X = v[0]
pts[idx].Y = v[1]
}
slice.Sort(pts, func(i, j int) bool {
return pts[i].X < pts[j].X
})
c.AddData(r.Name, pts, chart.PlotStyleLinesPoints, sched.Autostyle(ri))
}
w.Header().Set("Content-Type", "image/svg+xml")
white := color.RGBA{0xff, 0xff, 0xff, 0xff}
const width = 800
const height = 600
s := svg.New(w)
s.Start(width, height)
s.Rect(0, 0, width, height, "fill: #ffffff")
sgr := svgg.AddTo(s, 0, 0, width, height, "", 12, white)
c.Plot(sgr)
s.End()
return nil, nil
}
var a []annotate.Annotation
warnings := []string{}
if schedule.SystemConf.AnnotateEnabled() {
a, err = annotateBackend.GetAnnotations(&startT, &endT)
if err != nil {
warnings = append(warnings, fmt.Sprintf("unable to get annotations: %v", err))
}
}
return struct {
Queries []string
Series []*chartSeries
Annotations []annotate.Annotation
Warnings []string
}{
queries,
cs,
a,
warnings,
}, nil
}
// ExprGraph returns an svg graph.
// The basename of the requested svg file should be a base64 encoded expression.
func ExprGraph(t miniprofiler.Timer, w http.ResponseWriter, r *http.Request) (interface{}, error) {
vars := mux.Vars(r)
bs := vars["bs"]
format := vars["format"]
b, err := base64.StdEncoding.DecodeString(bs)
if err != nil {
return nil, err
}
q := string(b)
if len(q) == 0 {
return nil, fmt.Errorf("missing expression")
}
autods := 1000
if a := r.FormValue("autods"); a != "" {
i, err := strconv.Atoi(a)
if err != nil {
return nil, err
}
autods = i
}
now := time.Now().UTC()
if n := r.FormValue("now"); n != "" {
i, err := strconv.ParseInt(n, 10, 64)
if err != nil {
return nil, err
}
now = time.Unix(i, 0).UTC()
}
e, err := expr.New(q, schedule.RuleConf.GetFuncs(schedule.SystemConf.EnabledBackends()))
if err != nil {
return nil, err
} else if e.Root.Return() != models.TypeSeriesSet {
return nil, fmt.Errorf("egraph: requires an expression that returns a series")
}
// it may not strictly be necessary to recreate the contexts each time, but we do to be safe
backends := &expr.Backends{
TSDBContext: schedule.SystemConf.GetTSDBContext(),
GraphiteContext: schedule.SystemConf.GetGraphiteContext(),
InfluxConfig: schedule.SystemConf.GetInfluxContext(),
LogstashHosts: schedule.SystemConf.GetLogstashContext(),
ElasticHosts: schedule.SystemConf.GetElasticContext(),
AnnotateContext: schedule.SystemConf.GetAnnotateContext(),
}
providers := &expr.BosunProviders{
Cache: cacheObj,
Search: schedule.Search,
Squelched: nil,
History: nil,
}
res, _, err := e.Execute(backends, providers, t, now, autods, false)
if err != nil {
return nil, err
}
switch format {
case "svg":
if err := schedule.ExprSVG(t, w, 800, 600, "", res.Results); err != nil {
return nil, err
}
case "png":
if err := schedule.ExprPNG(t, w, 800, 600, "", res.Results); err != nil {
return nil, err
}
}
return nil, nil
}
func makeChart(r opentsdb.ResponseSet, m_units map[string]string) ([]*chartSeries, error) {
var series []*chartSeries
for _, resp := range r {
dps := make([][2]float64, 0)
for k, v := range resp.DPS {
ki, err := strconv.ParseInt(k, 10, 64)
if err != nil {
return nil, err
}
dps = append(dps, [2]float64{float64(ki), float64(v)})
}
if len(dps) > 0 {
slice.Sort(dps, func(i, j int) bool {
return dps[i][0] < dps[j][0]
})
name := resp.Metric
if len(resp.Tags) > 0 {
name += resp.Tags.String()
}
series = append(series, &chartSeries{
Name: name,
Metric: resp.Metric,
Tags: resp.Tags,
Data: dps,
Unit: m_units[resp.Metric],
})
}
}
return series, nil
}
type chartSeries struct {
Name string
Metric string
Tags opentsdb.TagSet
Data [][2]float64
Unit string
}