forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprometheus.go
114 lines (91 loc) Β· 2.47 KB
/
prometheus.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
package provider
import (
"context"
"fmt"
"math"
"time"
"github.com/evcc-io/evcc/util"
"github.com/evcc-io/evcc/util/request"
"github.com/evcc-io/evcc/util/transport"
"github.com/prometheus/client_golang/api"
v1 "github.com/prometheus/client_golang/api/prometheus/v1"
"github.com/prometheus/common/model"
)
// Prometheus provider
type Prometheus struct {
log *util.Logger
api v1.API
query string
timeout time.Duration
}
func init() {
registry.Add("prometheus", NewPrometheusFromConfig)
}
func NewPrometheusFromConfig(other map[string]interface{}) (Provider, error) {
cc := struct {
Uri, Query string
Timeout time.Duration
}{
Timeout: request.Timeout,
}
if err := util.DecodeOther(other, &cc); err != nil {
return nil, err
}
log := util.NewLogger("prometheus")
config := api.Config{
Address: cc.Uri,
RoundTripper: transport.Default(),
}
client, err := api.NewClient(config)
if err != nil {
return nil, err
}
p := NewPrometheus(log, client, cc.Query, cc.Timeout)
return p, nil
}
func NewPrometheus(log *util.Logger, client api.Client, query string, timeout time.Duration) *Prometheus {
p := &Prometheus{
log: log,
api: v1.NewAPI(client),
query: query,
timeout: timeout,
}
return p
}
func (p *Prometheus) Query() (model.Value, error) {
ctx, cancel := context.WithTimeout(context.Background(), p.timeout)
defer cancel()
res, warn, err := p.api.Query(ctx, p.query, time.Now())
if err != nil {
return nil, err
}
p.log.TRACE.Printf("query %q: %+v", p.query, res)
if len(warn) > 0 {
p.log.WARN.Printf("query %q returned warnings: %v", p.query, warn)
}
return res, nil
}
var _ FloatProvider = (*Prometheus)(nil)
// FloatGetter expects scalar value from query response as float
func (p *Prometheus) FloatGetter() (func() (float64, error), error) {
return func() (float64, error) {
res, err := p.Query()
if err != nil {
return 0, err
}
if res.Type() != model.ValScalar {
return 0, fmt.Errorf("query returned value of type %q, expected %q, consider wrapping query in scalar()", res.Type().String(), model.ValScalar.String())
}
scalarVal := res.(*model.Scalar)
return float64(scalarVal.Value), nil
}, nil
}
var _ IntProvider = (*Prometheus)(nil)
// IntGetter expects scalar value from query response as int
func (p *Prometheus) IntGetter() (func() (int64, error), error) {
g, err := p.FloatGetter()
return func() (int64, error) {
float, err := g()
return int64(math.Round(float)), err
}, err
}