forked from kuzaxak/promalert
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plotter.go
290 lines (252 loc) · 8.26 KB
/
plotter.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
package main
import (
"fmt"
"image/color"
"io"
"regexp"
"strconv"
"time"
"github.com/pkg/errors"
"github.com/prometheus/prometheus/promql/parser"
"github.com/prometheus/common/model"
"gonum.org/v1/plot"
"gonum.org/v1/plot/font"
"gonum.org/v1/plot/palette/brewer"
"gonum.org/v1/plot/plotter"
"gonum.org/v1/plot/vg"
"gonum.org/v1/plot/vg/draw"
"github.com/bugsnag/bugsnag-go/v2"
"github.com/bugsnag/microkit/clog"
"github.com/spf13/viper"
)
// Only show important part of metric name
var labelText = regexp.MustCompile("{(.*)}")
func GetPlotExpr(alertFormula string) []PlotExpr {
expr, _ := parser.ParseExpr(alertFormula)
if parenExpr, ok := expr.(*parser.ParenExpr); ok {
expr = parenExpr.Expr
clog.Infof("Removing redundant brackets: %v", expr.String())
}
if binaryExpr, ok := expr.(*parser.BinaryExpr); ok {
var alertOperator string
switch binaryExpr.Op {
case parser.LAND:
clog.Warn("Logical condition, drawing sides separately")
return append(GetPlotExpr(binaryExpr.LHS.String()), GetPlotExpr(binaryExpr.RHS.String())...)
case parser.LTE, parser.LSS:
alertOperator = "<"
case parser.GTE, parser.GTR:
alertOperator = ">"
default:
clog.Infof("Unexpected operator: %v", binaryExpr.Op.String())
alertOperator = ">"
}
alertLevel, _ := strconv.ParseFloat(binaryExpr.RHS.String(), 64)
return []PlotExpr{PlotExpr{
Formula: binaryExpr.LHS.String(),
Operator: alertOperator,
Level: alertLevel,
}}
} else {
clog.Infof("Non binary expression: %v", alertFormula)
return nil
}
}
func Plot(expr PlotExpr, queryTime time.Time, duration, resolution time.Duration, prometheusUrl string, alert Alert) (io.WriterTo, error) {
clog.Infof("Querying Prometheus %s", expr.Formula)
metrics, err := Metrics(
prometheusUrl,
expr.Formula,
queryTime,
duration,
resolution,
)
if err != nil {
_ = bugsnag.Notify(err,
bugsnag.MetaData{
"Expression": {
"PrometheusUrl": prometheusUrl,
"ExpressionFormula": expr.Formula,
"ExpressionOperator": expr.Operator,
"QueryTime": queryTime.String(),
},
"Alert": {
"Name": alert.Labels["alertname"],
"GeneratorURL": alert.GeneratorURL,
"Channel": alert.Channel,
"MessageTS": alert.MessageTS,
},
})
return nil, err
}
var selectedMetrics model.Matrix
var found bool
for _, metric := range metrics {
clog.Infof("Metric fetched: %v", metric.Metric)
found = false
for label, value := range metric.Metric {
if originValue, ok := alert.Labels[string(label)]; ok {
if originValue == string(value) {
found = true
} else {
found = false
break
}
}
}
if found {
clog.Infof("Best match found: %v", metric.Metric)
selectedMetrics = model.Matrix{metric}
break
}
}
if !found {
clog.Infof("Best match not found, use entire dataset. Labels to search: %v", alert.Labels)
selectedMetrics = metrics
}
clog.Infof("Creating plot: %s", alert.Annotations["summary"])
plottedMetric, err := PlotMetric(selectedMetrics, expr.Level, expr.Operator)
if err != nil {
_ = bugsnag.Notify(err,
bugsnag.MetaData{
"Expression": {
"PrometheusUrl": prometheusUrl,
"ExpressionFormula": expr.Formula,
"ExpressionOperator": expr.Operator,
"QueryTime": queryTime.String(),
},
"Alert": {
"Name": alert.Labels["name"],
"GeneratorURL": alert.GeneratorURL,
"Channel": alert.Channel,
"MessageTS": alert.MessageTS,
},
})
return nil, err
}
return plottedMetric, nil
}
func PlotMetric(metrics model.Matrix, level float64, direction string) (io.WriterTo, error) {
viper.SetDefault("graph_scale", 1.0)
var graphScale = viper.GetFloat64("graph_scale")
textFontDef := font.Font{Typeface: "Liberation", Variant: "Mono"}
textFont := font.DefaultCache.Lookup(textFontDef, vg.Length(2.5*graphScale)*vg.Millimeter)
if textFont.Name() == "" {
clog.Error("Failed to lookup text font")
return nil, errors.New("failed to lookup text font")
}
evalTextFont := font.DefaultCache.Lookup(textFontDef, vg.Length(3*graphScale)*vg.Millimeter)
evalTextStyle := draw.TextStyle{
Color: color.NRGBA{A: 150},
Font: evalTextFont.Font,
XAlign: draw.XRight,
YAlign: draw.YBottom,
Handler: plot.DefaultTextHandler,
}
p := plot.New()
//p.Y.Min = 0
p.X.Tick.Marker = plot.TimeTicks{Format: "15:04:05"}
p.X.Tick.Label.Font = textFont.Font
p.Y.Tick.Label.Font = textFont.Font
p.Legend.TextStyle.Font = textFont.Font
p.Legend.Top = true
p.Legend.YOffs = vg.Length(15*graphScale) * vg.Millimeter
// Color palette for drawing lines
paletteSize := 8
palette, err := brewer.GetPalette(brewer.TypeAny, "Dark2", paletteSize)
if err != nil {
return nil, errors.Wrap(err, "failed to get color palette")
}
colors := palette.Colors()
var lastEvalValue float64
for s, sample := range metrics {
data := make(plotter.XYs, 0)
for _, v := range sample.Values {
fs := v.Value.String()
if fs == "NaN" {
_, err := drawLine(data, colors, s, paletteSize, p, metrics, sample)
if err != nil {
return nil, errors.Wrapf(err, "failed to draw line for value: %s", v.Value.String())
}
data = make(plotter.XYs, 0)
continue
}
f, err := strconv.ParseFloat(fs, 64)
if err != nil {
return nil, errors.Wrap(err, "sample value not float: "+v.Value.String())
}
data = append(data, plotter.XY{X: float64(v.Timestamp.Unix()), Y: f})
lastEvalValue = f
}
_, err := drawLine(data, colors, s, paletteSize, p, metrics, sample)
if err != nil {
return nil, err
}
}
var polygonPoints plotter.XYs
if direction == "<" {
polygonPoints = plotter.XYs{{X: p.X.Min, Y: level}, {X: p.X.Max, Y: level}, {X: p.X.Max, Y: p.Y.Min}, {X: p.X.Min, Y: p.Y.Min}}
} else {
polygonPoints = plotter.XYs{{X: p.X.Min, Y: level}, {X: p.X.Max, Y: level}, {X: p.X.Max, Y: p.Y.Max}, {X: p.X.Min, Y: p.Y.Max}}
}
poly, err := plotter.NewPolygon(polygonPoints)
if err != nil {
polyErr := errors.Wrap(err, "failed to create polygon")
//nolint:errcheck // intentionally ignoring the error from Bugsnag notification
bugsnag.Notify(polyErr, bugsnag.MetaData{
"Graph": {
"PolygonPoints": polygonPoints,
"Metrics": metrics,
},
})
return nil, polyErr
}
poly.Color = color.NRGBA{R: 255, A: 40}
poly.LineStyle.Color = color.NRGBA{R: 0, A: 0}
p.Add(poly)
p.Add(plotter.NewGrid())
// Draw plot in canvas with margin
margin := vg.Length(3*graphScale) * vg.Millimeter
width := vg.Length(12*graphScale) * vg.Centimeter
height := vg.Length(6*graphScale) * vg.Centimeter
c, err := draw.NewFormattedCanvas(width, height, "png")
if err != nil {
return nil, errors.Wrap(err, "failed to create canvas")
}
croppedCanvas := draw.Crop(draw.New(c), margin, -margin, margin, -margin)
p.Draw(croppedCanvas)
// Draw last evaluated value
evalText := fmt.Sprintf("latest evaluation: %.2f", lastEvalValue)
plotterCanvas := p.DataCanvas(croppedCanvas)
trX, trY := p.Transforms(&plotterCanvas)
evalRectangle := evalTextStyle.Rectangle(evalText)
points := []vg.Point{
{X: trX(p.X.Max) + evalRectangle.Min.X - 8*vg.Millimeter, Y: trY(lastEvalValue) + evalRectangle.Min.Y - vg.Millimeter},
{X: trX(p.X.Max) + evalRectangle.Min.X - 8*vg.Millimeter, Y: trY(lastEvalValue) + evalRectangle.Max.Y + vg.Millimeter},
{X: trX(p.X.Max) + evalRectangle.Max.X - 6*vg.Millimeter, Y: trY(lastEvalValue) + evalRectangle.Max.Y + vg.Millimeter},
{X: trX(p.X.Max) + evalRectangle.Max.X - 6*vg.Millimeter, Y: trY(lastEvalValue) + evalRectangle.Min.Y - vg.Millimeter},
}
plotterCanvas.FillPolygon(color.NRGBA{R: 255, G: 255, B: 255, A: 90}, points)
plotterCanvas.FillText(evalTextStyle, vg.Point{X: trX(p.X.Max) - 6*vg.Millimeter, Y: trY(lastEvalValue)}, evalText)
return c, nil
}
func drawLine(data plotter.XYs, colors []color.Color, s int, paletteSize int, p *plot.Plot, metrics model.Matrix, sample *model.SampleStream) (*plotter.Line, error) {
var l *plotter.Line
var err error
if len(data) > 0 {
l, err = plotter.NewLine(data)
if err != nil {
return &plotter.Line{}, errors.Wrap(err, "failed to create line")
}
l.LineStyle.Width = vg.Points(1)
l.LineStyle.Color = colors[s%paletteSize]
p.Add(l)
if len(metrics) > 1 {
m := labelText.FindStringSubmatch(sample.Metric.String())
if m != nil {
p.Legend.Add(m[1], l)
}
}
}
return l, nil
}