-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinput_prometheus.go
83 lines (70 loc) · 1.96 KB
/
input_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
package prometheus
import (
"context"
"time"
"github.com/JorTurFer/xk6-input-prometheus/utils"
"github.com/prometheus/client_golang/api"
v1 "github.com/prometheus/client_golang/api/prometheus/v1"
"github.com/prometheus/common/config"
"github.com/prometheus/common/model"
"go.k6.io/k6/js/modules"
)
// init is called by the Go runtime at application startup.
func init() {
modules.Register("k6/x/prometheusread", new(Prometheus))
}
type Prometheus struct{}
type Client struct {
url string
username string
password config.Secret
}
func (*Prometheus) NewPrometheusClient(url, username string, password config.Secret) Client {
return Client{
url: url,
username: username,
password: password,
}
}
func (c *Client) Query(query string) (model.Value, error) {
client, err := c.generateClient()
if err != nil {
return nil, err
}
v1api := v1.NewAPI(client)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
result, warnings, err := v1api.Query(ctx, query, time.Now(), v1.WithTimeout(5*time.Second))
if err != nil || len(warnings) > 0 {
return nil, err
}
return result, nil
}
func (c *Client) QueryRange(query, start, end, period string) (model.Value, error) {
client, err := c.generateClient()
if err != nil {
return nil, err
}
r, err := utils.ParseRange(start, end, period)
if err != nil {
return nil, err
}
v1api := v1.NewAPI(client)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
result, warnings, err := v1api.QueryRange(ctx, query, r, v1.WithTimeout(5*time.Second))
if err != nil || len(warnings) > 0 {
return nil, err
}
return result, nil
}
func (c *Client) generateClient() (api.Client, error) {
roundTripper := api.DefaultRoundTripper
if c.password != "" {
roundTripper = config.NewBasicAuthRoundTripper(c.username, c.password, "", api.DefaultRoundTripper)
}
return api.NewClient(api.Config{
Address: c.url,
RoundTripper: roundTripper,
})
}