-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathmetrics.go
90 lines (80 loc) · 1.91 KB
/
metrics.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
package gohalt
import (
"context"
"fmt"
"sync"
"time"
client "github.com/prometheus/client_golang/api"
prometheus "github.com/prometheus/client_golang/api/prometheus/v1"
"github.com/prometheus/common/model"
)
type Metric interface {
Query(context.Context) (bool, error)
}
type mtcprometheus struct {
mempull Runnable
value bool
}
func NewMetricPrometheus(url string, query string, cache time.Duration, mstep time.Duration) *mtcprometheus {
mtc := &mtcprometheus{}
var lock sync.Mutex
var api prometheus.API
mtc.mempull = cached(cache, func(ctx context.Context) (err error) {
lock.Lock()
defer lock.Unlock()
if api != nil {
return mtc.pull(ctx, api, cache, mstep, query)
}
api, err = mtc.connect(ctx, url)
if err != nil {
return err
}
return mtc.pull(ctx, api, cache, mstep, query)
})
return mtc
}
func (mtc *mtcprometheus) Query(ctx context.Context) (bool, error) {
if err := mtc.mempull(ctx); err != nil {
return mtc.value, err
}
return mtc.value, nil
}
func (mtc mtcprometheus) connect(_ context.Context, url string) (prometheus.API, error) {
client, err := client.NewClient(
client.Config{
Address: url,
RoundTripper: client.DefaultRoundTripper,
},
)
if err != nil {
return nil, err
}
return prometheus.NewAPI(client), nil
}
func (mtc *mtcprometheus) pull(
ctx context.Context,
api prometheus.API,
cache time.Duration,
mstep time.Duration,
query string,
) error {
timestamp := time.Now().UTC()
val, _, err := api.QueryRange(ctx, query, prometheus.Range{
Start: timestamp,
End: timestamp.Add(cache),
Step: mstep,
})
scalar, ok := val.(*model.Scalar)
if !ok || (scalar.Value != 0 && scalar.Value != 1) {
return fmt.Errorf("boolean metric value expected instead of %v", val)
}
mtc.value = scalar.Value == 1
return err
}
type mtcmock struct {
metric bool
err error
}
func (mtc mtcmock) Query(context.Context) (bool, error) {
return mtc.metric, mtc.err
}