-
Notifications
You must be signed in to change notification settings - Fork 5
/
renderer.go
102 lines (91 loc) · 2.18 KB
/
renderer.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
package renderer
import (
"context"
"errors"
"io"
"sort"
"strings"
"time"
"github.com/prometheus/client_golang/api"
"github.com/prometheus/client_golang/api/prometheus/v1"
"github.com/prometheus/common/model"
"gonum.org/v1/plot"
"gonum.org/v1/plot/plotter"
"gonum.org/v1/plot/plotutil"
"gonum.org/v1/plot/vg"
"gonum.org/v1/plot/vg/draw"
"gonum.org/v1/plot/vg/vgimg"
)
type Render struct {
v1.API
}
func New(prometheusURL string) (*Render, error) {
client, err := api.NewClient(api.Config{Address: prometheusURL})
if err != nil {
return nil, err
}
return &Render{
API: v1.NewAPI(client),
}, nil
}
func (r *Render) Render(w io.Writer, query string, start, end time.Time, ws, hs int, legend bool) error {
plot, err := plot.New()
if err != nil {
return err
}
plot.Legend.Top = true
timeseries, err := r.queryRange(query, start, end, legend)
if err != nil {
return err
}
if err := plotutil.AddLinePoints(plot, timeseries...); err != nil {
return err
}
plot.Y.Max = plot.Y.Max * 1.2
c := vgimg.New(vg.Length(ws), vg.Length(hs))
cpng := vgimg.PngCanvas{Canvas: c}
cv := draw.New(cpng)
plot.Draw(cv)
_, err = cpng.WriteTo(w)
return err
}
// returns name, plotter.XYer, name1, plotter.XYer ...
func (r *Render) queryRange(query string, start, end time.Time, legend bool) ([]interface{}, error) {
now := time.Now()
resp, err := r.API.QueryRange(context.Background(), query, v1.Range{
Start: start,
End: end,
Step: 60 * time.Second,
})
if err != nil {
return nil, err
}
matrix, ok := resp.(model.Matrix)
if !ok {
return nil, errors.New("Expected matrix")
}
sort.Sort(matrix)
ret := make([]interface{}, 0)
for _, ss := range matrix {
pts := make(plotter.XYs, len(ss.Values))
for i, sample := range ss.Values {
pts[i].Y = float64(sample.Value)
pts[i].X = float64(sample.Timestamp.Unix()-now.Unix()) / 60
}
if legend {
ret = append(ret, formatMetric(ss.Metric))
}
ret = append(ret, pts)
}
return ret, nil
}
func formatMetric(m model.Metric) string {
ls := model.LabelSet(m)
values := make([]string, len(ls))
i := 0
for _, v := range ls {
values[i] = strings.Replace(string(v), "\n", " ", -1)
i++
}
return strings.Join(values, "|")
}