This repository has been archived by the owner on Oct 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
/
client.go
108 lines (86 loc) · 2.11 KB
/
client.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
package prometheus
import (
"bytes"
"context"
"text/template"
"github.com/deislabs/smi-sdk-go/pkg/apis/metrics"
"github.com/masterminds/sprig"
promAPI "github.com/prometheus/client_golang/api/prometheus/v1"
"github.com/prometheus/common/model"
log "github.com/sirupsen/logrus"
apiresource "k8s.io/apimachinery/pkg/api/resource"
)
type Query struct {
Template string
Name string
Values map[string]interface{}
}
type Lookup interface {
Get(edge model.Metric) *metrics.TrafficMetrics
Queries() []*Query
}
type Client struct {
ctx context.Context
client promAPI.API
interval *metrics.Interval
}
func NewClient(
ctx context.Context,
client promAPI.API,
interval *metrics.Interval) *Client {
return &Client{
ctx: ctx,
client: client,
interval: interval,
}
}
func (c *Client) render(
query string, opts map[string]interface{}) (string, error) {
buf := &bytes.Buffer{}
opts["window"] = c.interval.Window.Duration.String()
tmpl, err := template.New("query").Funcs(sprig.TxtFuncMap()).Parse(query)
if err != nil {
return "", err
}
if err := tmpl.Execute(buf, opts); err != nil {
return "", err
}
return buf.String(), nil
}
func (c *Client) Execute(
queryTemplate string, opts map[string]interface{}) (model.Vector, error) {
query, err := c.render(queryTemplate, opts)
if err != nil {
return nil, err
}
log.WithFields(log.Fields{
"query": query,
}).Debug("querying prometheus")
result, err := c.client.Query(c.ctx, query, c.interval.Timestamp.Time)
if err != nil {
return nil, err
}
log.WithFields(log.Fields{
"query": query,
"result": result.String(),
}).Debug("query results")
return result.(model.Vector), nil
}
func (c *Client) Update(lst Lookup) error {
for _, query := range lst.Queries() {
result, err := c.Execute(query.Template, query.Values)
if err != nil {
return err
}
for _, sample := range result {
resource := lst.Get(sample.Metric)
metric := resource.Get(query.Name)
if metric.Name == "" {
continue
}
metric.Value = apiresource.NewMilliQuantity(
int64(sample.Value*1000), apiresource.DecimalSI)
}
}
return nil
}