cloudflare/pint

Public

mirrored from https://github.com/cloudflare/pintAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v0.62.0

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

internal/promapi/config.go

163lines · modecode

1package promapi
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "io"
8 "log/slog"
9 "net/http"
10 "net/url"
11 "time"
12
13 v1 "github.com/prometheus/client_golang/api/prometheus/v1"
14 "github.com/prymitive/current"
15 "gopkg.in/yaml.v3"
16)
17
18type ConfigSectionGlobal struct {
19 ExternalLabels map[string]string `yaml:"external_labels"`
20 ScrapeInterval time.Duration `yaml:"scrape_interval"`
21 ScrapeTimeout time.Duration `yaml:"scrape_timeout"`
22 EvaluationInterval time.Duration `yaml:"evaluation_interval"`
23}
24
25type PrometheusConfig struct {
26 RuleFiles []string `yaml:"rule_files"`
27 Global ConfigSectionGlobal `yaml:"global"`
28}
29
30type ConfigResult struct {
31 URI string
32 Config PrometheusConfig
33}
34
35type configQuery struct {
36 prom *Prometheus
37 ctx context.Context
38 timestamp time.Time
39 cacheTTL time.Duration
40}
41
42func (q configQuery) Run() queryResult {
43 slog.Debug("Getting prometheus configuration", slog.String("uri", q.prom.safeURI))
44
45 ctx, cancel := q.prom.requestContext(q.ctx)
46 defer cancel()
47
48 var qr queryResult
49
50 args := url.Values{}
51 resp, err := q.prom.doRequest(ctx, http.MethodGet, q.Endpoint(), args)
52 if err != nil {
53 qr.err = fmt.Errorf("failed to query Prometheus config: %w", err)
54 return qr
55 }
56 defer resp.Body.Close()
57
58 if resp.StatusCode/100 != 2 {
59 qr.err = tryDecodingAPIError(resp)
60 return qr
61 }
62
63 qr.value, err = streamConfig(resp.Body)
64 if err != nil {
65 prometheusQueryErrorsTotal.WithLabelValues(q.prom.name, "/api/v1/status/config", errReason(err)).Inc()
66 qr.err = fmt.Errorf("failed to decode config data in %s response: %w", q.prom.safeURI, err)
67 }
68 return qr
69}
70
71func (q configQuery) Endpoint() string {
72 return "/api/v1/status/config"
73}
74
75func (q configQuery) String() string {
76 return "/api/v1/status/config"
77}
78
79func (q configQuery) CacheKey() uint64 {
80 return hash(q.prom.unsafeURI, q.Endpoint())
81}
82
83func (q configQuery) CacheTTL() time.Duration {
84 return q.cacheTTL
85}
86
87func (p *Prometheus) Config(ctx context.Context, cacheTTL time.Duration) (*ConfigResult, error) {
88 slog.Debug("Scheduling Prometheus configuration query", slog.String("uri", p.safeURI))
89
90 key := "/api/v1/status/config"
91 p.locker.lock(key)
92 defer p.locker.unlock(key)
93
94 if cacheTTL == 0 {
95 cacheTTL = time.Minute
96 }
97
98 resultChan := make(chan queryResult)
99 p.queries <- queryRequest{
100 query: configQuery{prom: p, ctx: ctx, timestamp: time.Now(), cacheTTL: cacheTTL},
101 result: resultChan,
102 }
103
104 result := <-resultChan
105 if result.err != nil {
106 return nil, QueryError{err: result.err, msg: decodeError(result.err)}
107 }
108
109 r := ConfigResult{
110 URI: p.publicURI,
111 Config: result.value.(PrometheusConfig),
112 }
113
114 return &r, nil
115}
116
117func streamConfig(r io.Reader) (cfg PrometheusConfig, err error) {
118 defer dummyReadAll(r)
119
120 var yamlBody, status, errType, errText string
121 errText = "empty response object"
122 decoder := current.Object(
123 current.Key("status", current.Value(func(s string, _ bool) {
124 status = s
125 })),
126 current.Key("error", current.Value(func(s string, _ bool) {
127 errText = s
128 })),
129 current.Key("errorType", current.Value(func(s string, _ bool) {
130 errType = s
131 })),
132 current.Key("data", current.Object(
133 current.Key("yaml", current.Value(func(s string, _ bool) {
134 yamlBody = s
135 })),
136 )),
137 )
138
139 dec := json.NewDecoder(r)
140 if err = decoder.Stream(dec); err != nil {
141 return cfg, APIError{Status: status, ErrorType: v1.ErrBadResponse, Err: fmt.Sprintf("JSON parse error: %s", err)}
142 }
143
144 if status != "success" {
145 return cfg, APIError{Status: status, ErrorType: decodeErrorType(errType), Err: errText}
146 }
147
148 if err = yaml.Unmarshal([]byte(yamlBody), &cfg); err != nil {
149 return cfg, err
150 }
151
152 if cfg.Global.ScrapeInterval == 0 {
153 cfg.Global.ScrapeInterval = time.Minute
154 }
155 if cfg.Global.ScrapeTimeout == 0 {
156 cfg.Global.ScrapeTimeout = time.Second * 10
157 }
158 if cfg.Global.EvaluationInterval == 0 {
159 cfg.Global.EvaluationInterval = time.Minute
160 }
161
162 return cfg, nil
163}