/
prometheus.go
62 lines (55 loc) · 1.7 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
package prometheus
import (
"context"
"crypto/tls"
"fmt"
"net/http"
"time"
prometheusapi "github.com/prometheus/client_golang/api"
v1 "github.com/prometheus/client_golang/api/prometheus/v1"
"github.com/prometheus/common/model"
)
type PrometheusClient struct {
v1.API
}
var PrometheusURL string
func (p PrometheusClient) GetHistogramQuantileLatency(percentile, checkKey, duration string) (latency float64, err error) {
modelValue, _, err := p.Query(context.TODO(), fmt.Sprintf("histogram_quantile(%v, sum(rate(canary_check_duration_bucket{key='%v'}[%v])) by (le))", percentile, checkKey, duration), time.Now())
if err != nil {
return 0, err
}
if modelValue == nil {
return 0, nil
}
return float64(modelValue.(model.Vector)[0].Value), nil
}
func (p PrometheusClient) GetUptime(checkKey, duration string) (float64, error) {
success := fmt.Sprintf("rate(canary_check_success_count{key='%v'}[%v])", checkKey, duration)
failed := fmt.Sprintf("rate(canary_check_failed_count{key='%v'}[%v])", checkKey, duration)
uptime, _, err := p.Query(context.TODO(), fmt.Sprintf("%s/%s + %s", failed, failed, success), time.Now())
if err != nil {
return 0, err
}
return 100 - float64(uptime.(model.Vector)[0].Value), nil
}
func NewPrometheusAPI(url string) (*PrometheusClient, error) {
if url == "" {
return nil, nil
}
transportConfig := prometheusapi.DefaultRoundTripper.(*http.Transport)
transportConfig.TLSClientConfig = &tls.Config{
InsecureSkipVerify: true,
}
cfg := prometheusapi.Config{
Address: url,
RoundTripper: transportConfig,
}
client, err := prometheusapi.NewClient(cfg)
if err != nil {
return nil, err
}
promapi := v1.NewAPI(client)
return &PrometheusClient{
API: promapi,
}, nil
}