/
prometheus.go
151 lines (126 loc) · 3.73 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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
package providers
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"path"
"regexp"
"strconv"
"time"
flaggerv1 "github.com/weaveworks/flagger/pkg/apis/flagger/v1beta1"
)
const prometheusOnlineQuery = "vector(1)"
// PrometheusProvider executes promQL queries
type PrometheusProvider struct {
timeout time.Duration
url url.URL
username string
password string
}
type prometheusResponse struct {
Data struct {
Result []struct {
Metric struct {
Name string `json:"name"`
}
Value []interface{} `json:"value"`
}
}
}
// NewPrometheusProvider takes a provider spec and the credentials map,
// validates the address, extracts the username and password values if provided and
// returns a Prometheus client ready to execute queries against the API
func NewPrometheusProvider(provider flaggerv1.MetricTemplateProvider, credentials map[string][]byte) (*PrometheusProvider, error) {
promURL, err := url.Parse(provider.Address)
if provider.Address == "" || err != nil {
return nil, fmt.Errorf("%s address %s is not a valid URL", provider.Type, provider.Address)
}
prom := PrometheusProvider{
timeout: 5 * time.Second,
url: *promURL,
}
if provider.SecretRef != nil {
if username, ok := credentials["username"]; ok {
prom.username = string(username)
} else {
return nil, fmt.Errorf("%s credentials does not contain a username", provider.Type)
}
if password, ok := credentials["password"]; ok {
prom.password = string(password)
} else {
return nil, fmt.Errorf("%s credentials does not contain a password", provider.Type)
}
}
return &prom, nil
}
// RunQuery executes the promQL query and returns the the first result as float64
func (p *PrometheusProvider) RunQuery(query string) (float64, error) {
query = url.QueryEscape(p.trimQuery(query))
u, err := url.Parse(fmt.Sprintf("./api/v1/query?query=%s", query))
if err != nil {
return 0, fmt.Errorf("url.Parase failed: %w", err)
}
u.Path = path.Join(p.url.Path, u.Path)
u = p.url.ResolveReference(u)
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return 0, fmt.Errorf("http.NewRequest failed: %w", err)
}
if p.username != "" && p.password != "" {
req.SetBasicAuth(p.username, p.password)
}
ctx, cancel := context.WithTimeout(req.Context(), p.timeout)
defer cancel()
r, err := http.DefaultClient.Do(req.WithContext(ctx))
if err != nil {
return 0, fmt.Errorf("request failed: %w", err)
}
defer r.Body.Close()
b, err := ioutil.ReadAll(r.Body)
if err != nil {
return 0, fmt.Errorf("error reading body: %w", err)
}
if 400 <= r.StatusCode {
return 0, fmt.Errorf("error response: %s", string(b))
}
var result prometheusResponse
err = json.Unmarshal(b, &result)
if err != nil {
return 0, fmt.Errorf("error unmarshaling result: %w, '%s'", err, string(b))
}
var value *float64
for _, v := range result.Data.Result {
metricValue := v.Value[1]
switch metricValue.(type) {
case string:
f, err := strconv.ParseFloat(metricValue.(string), 64)
if err != nil {
return 0, err
}
value = &f
}
}
if value == nil {
return 0, fmt.Errorf("%w", ErrNoValuesFound)
}
return *value, nil
}
// IsOnline run simple Prometheus query and returns an error if the API is unreachable
func (p *PrometheusProvider) IsOnline() (bool, error) {
value, err := p.RunQuery(prometheusOnlineQuery)
if err != nil {
return false, fmt.Errorf("running query failed: %w", err)
}
if value != float64(1) {
return false, fmt.Errorf("value is not 1 for query: %s", prometheusOnlineQuery)
}
return true, nil
}
// trimQuery takes a promql query and removes whitespace
func (p *PrometheusProvider) trimQuery(query string) string {
space := regexp.MustCompile(`\s+`)
return space.ReplaceAllString(query, " ")
}