/
prometheus.go
280 lines (242 loc) · 7.08 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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
package config
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"go/parser"
"log/slog"
"net/url"
"os"
"regexp"
"strings"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/cloudflare/pint/internal/promapi"
)
type TLSConfig struct {
ServerName string `hcl:"serverName,optional" json:"serverName,omitempty"`
CaCert string `hcl:"caCert,optional" json:"caCert,omitempty"`
ClientCert string `hcl:"clientCert,optional" json:"clientCert,omitempty"`
ClientKey string `hcl:"clientKey,optional" json:"clientKey,omitempty"`
InsecureSkipVerify bool `hcl:"skipVerify,optional" json:"skipVerify,omitempty"`
}
func (t TLSConfig) validate() error {
if (t.ClientCert != "") != (t.ClientKey != "") {
return fmt.Errorf("clientCert and clientKey must be set together")
}
return nil
}
func (t *TLSConfig) toHTTPConfig() (*tls.Config, error) {
if t == nil {
return nil, nil
}
var isDirty bool
cfg := &tls.Config{}
if t.ServerName != "" {
cfg.ServerName = t.ServerName
isDirty = true
}
if t.CaCert != "" {
caCert, err := os.ReadFile(t.CaCert)
if err != nil {
return nil, err
}
cfg.RootCAs = x509.NewCertPool()
cfg.RootCAs.AppendCertsFromPEM(caCert)
isDirty = true
}
if t.ClientCert != "" && t.ClientKey != "" {
cert, err := tls.LoadX509KeyPair(t.ClientCert, t.ClientKey)
if err != nil {
return nil, err
}
cfg.Certificates = []tls.Certificate{cert}
isDirty = true
}
if t.InsecureSkipVerify {
cfg.InsecureSkipVerify = true
isDirty = true
}
if isDirty {
return cfg, nil
}
return nil, nil
}
type PrometheusConfig struct {
Headers map[string]string `hcl:"headers,optional" json:"headers,omitempty"`
TLS *TLSConfig `hcl:"tls,block" json:"tls,omitempty"`
Name string `hcl:",label" json:"name"`
URI string `hcl:"uri" json:"uri"`
PublicURI string `hcl:"publicURI,optional" json:"publicURI,omitempty"`
Timeout string `hcl:"timeout,optional" json:"timeout"`
Uptime string `hcl:"uptime,optional" json:"uptime"`
Failover []string `hcl:"failover,optional" json:"failover,omitempty"`
Include []string `hcl:"include,optional" json:"include,omitempty"`
Exclude []string `hcl:"exclude,optional" json:"exclude,omitempty"`
Tags []string `hcl:"tags,optional" json:"tags,omitempty"`
Concurrency int `hcl:"concurrency,optional" json:"concurrency"`
RateLimit int `hcl:"rateLimit,optional" json:"rateLimit"`
Required bool `hcl:"required,optional" json:"required"`
}
func (pc PrometheusConfig) validate() error {
if pc.URI == "" {
return errors.New("prometheus URI cannot be empty")
}
if _, err := url.Parse(pc.URI); err != nil {
return fmt.Errorf("prometheus URI %q is invalid: %w", pc.URI, err)
}
if pc.Timeout != "" {
if _, err := parseDuration(pc.Timeout); err != nil {
return err
}
}
if pc.Uptime != "" {
if _, err := parser.ParseExpr(pc.Uptime); err != nil {
return fmt.Errorf("invalid Prometheus uptime metric selector %q: %w", pc.Uptime, err)
}
}
for _, path := range pc.Include {
if _, err := regexp.Compile(path); err != nil {
return err
}
}
for _, path := range pc.Exclude {
if _, err := regexp.Compile(path); err != nil {
return err
}
}
for _, tag := range pc.Tags {
for _, s := range []string{" ", "\n"} {
if strings.Contains(tag, s) {
return fmt.Errorf("prometheus tag %q cannot contain %q", tag, s)
}
}
}
if pc.TLS != nil {
if err := pc.TLS.validate(); err != nil {
return err
}
}
return nil
}
func (pc *PrometheusConfig) applyDefaults() {
if pc.Timeout == "" {
pc.Timeout = (time.Minute * 2).String()
}
if pc.Concurrency <= 0 {
pc.Concurrency = 16
}
if pc.RateLimit <= 0 {
pc.RateLimit = 100
}
if pc.Uptime == "" {
pc.Uptime = "up"
}
}
func newFailoverGroup(prom PrometheusConfig) *promapi.FailoverGroup {
timeout, _ := parseDuration(prom.Timeout)
var tlsConf *tls.Config
tlsConf, _ = prom.TLS.toHTTPConfig()
upstreams := []*promapi.Prometheus{
promapi.NewPrometheus(prom.Name, prom.URI, prom.PublicURI, prom.Headers, timeout, prom.Concurrency, prom.RateLimit, tlsConf),
}
for _, uri := range prom.Failover {
upstreams = append(upstreams, promapi.NewPrometheus(prom.Name, uri, prom.PublicURI, prom.Headers, timeout, prom.Concurrency, prom.RateLimit, tlsConf))
}
include := make([]*regexp.Regexp, 0, len(prom.Include))
for _, path := range prom.Include {
include = append(include, strictRegex(path))
}
exclude := make([]*regexp.Regexp, 0, len(prom.Exclude))
for _, path := range prom.Exclude {
exclude = append(exclude, strictRegex(path))
}
tags := make([]string, 0, len(prom.Tags))
tags = append(tags, prom.Tags...)
return promapi.NewFailoverGroup(prom.Name, prom.PublicURI, upstreams, prom.Required, prom.Uptime, include, exclude, tags)
}
func NewPrometheusGenerator(cfg Config, metricsRegistry *prometheus.Registry) *PrometheusGenerator {
return &PrometheusGenerator{
metricsRegistry: metricsRegistry,
cfg: cfg,
}
}
type PrometheusGenerator struct {
cfg Config
metricsRegistry *prometheus.Registry
servers []*promapi.FailoverGroup
}
func (pg *PrometheusGenerator) Servers() []*promapi.FailoverGroup {
return pg.servers
}
func (pg *PrometheusGenerator) Count() int {
return len(pg.servers)
}
func (pg *PrometheusGenerator) Stop() {
for _, server := range pg.servers {
server.Close(pg.metricsRegistry)
}
pg.servers = nil
}
func (pg *PrometheusGenerator) ServersForPath(path string) []*promapi.FailoverGroup {
var servers []*promapi.FailoverGroup
for _, server := range pg.servers {
if server.IsEnabledForPath(path) {
servers = append(servers, server)
}
}
return servers
}
func (pg *PrometheusGenerator) ServerWithName(name string) *promapi.FailoverGroup {
for _, server := range pg.servers {
if server.Name() == name {
return server
}
}
return nil
}
func (pg *PrometheusGenerator) addServer(server *promapi.FailoverGroup) error {
for _, s := range pg.servers {
if s.Name() == server.Name() {
return fmt.Errorf("Duplicated name for Prometheus server definition: %s", s.Name())
}
}
pg.servers = append(pg.servers, server)
slog.Info(
"Configured new Prometheus server",
slog.String("name", server.Name()),
slog.Int("uris", server.ServerCount()),
slog.String("uptime", server.UptimeMetric()),
slog.Any("tags", server.Tags()),
slog.Any("include", server.Include()),
slog.Any("exclude", server.Exclude()),
)
server.StartWorkers(pg.metricsRegistry)
return nil
}
func (pg *PrometheusGenerator) GenerateStatic() (err error) {
for _, pc := range pg.cfg.Prometheus {
err = pg.addServer(newFailoverGroup(pc))
if err != nil {
return err
}
}
return nil
}
func (pg *PrometheusGenerator) GenerateDynamic(ctx context.Context) (err error) {
if pg.cfg.Discovery != nil {
servers, err := pg.cfg.Discovery.Discover(ctx)
if err != nil {
return err
}
for _, server := range servers {
err = pg.addServer(server)
if err != nil {
return err
}
}
}
return nil
}