cloudflare/pint

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v0.32.0

Branches

Tags

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

Clone

HTTPS

Download ZIP

internal/promapi/metadata.go

127lines · modecode

1package promapi
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "io"
8 "net/http"
9 "net/url"
10 "time"
11
12 v1 "github.com/prometheus/client_golang/api/prometheus/v1"
13 "github.com/prymitive/current"
14 "github.com/rs/zerolog/log"
15)
16
17type MetadataResult struct {
18 URI string
19 Metadata []v1.Metadata
20}
21
22type metadataQuery struct {
23 prom *Prometheus
24 ctx context.Context
25 metric string
26 timestamp time.Time
27}
28
29func (q metadataQuery) Run() queryResult {
30 log.Debug().
31 Str("uri", q.prom.safeURI).
32 Str("metric", q.metric).
33 Msg("Getting prometheus metrics metadata")
34
35 ctx, cancel := context.WithTimeout(q.ctx, q.prom.timeout)
36 defer cancel()
37
38 qr := queryResult{expires: q.timestamp.Add(cacheExpiry * 2)}
39
40 args := url.Values{}
41 args.Set("metric", q.metric)
42 resp, err := q.prom.doRequest(ctx, http.MethodGet, q.Endpoint(), args)
43 if err != nil {
44 qr.err = fmt.Errorf("failed to query Prometheus metrics metadata: %w", err)
45 return qr
46 }
47 defer resp.Body.Close()
48
49 if resp.StatusCode/100 != 2 {
50 qr.err = tryDecodingAPIError(resp)
51 return qr
52 }
53
54 qr.value, qr.err = streamMetadata(resp.Body)
55 return qr
56}
57
58func (q metadataQuery) Endpoint() string {
59 return "/api/v1/metadata"
60}
61
62func (q metadataQuery) String() string {
63 return q.metric
64}
65
66func (q metadataQuery) CacheAfter() int {
67 return 0
68}
69
70func (q metadataQuery) CacheKey() uint64 {
71 return hash(q.prom.unsafeURI, q.Endpoint(), q.metric, q.timestamp.Round(cacheExpiry).Format(time.RFC3339))
72}
73
74func (p *Prometheus) Metadata(ctx context.Context, metric string) (*MetadataResult, error) {
75 log.Debug().Str("uri", p.safeURI).Str("metric", metric).Msg("Scheduling Prometheus metrics metadata query")
76
77 key := fmt.Sprintf("/api/v1/metadata/%s", metric)
78 p.locker.lock(key)
79 defer p.locker.unlock(key)
80
81 resultChan := make(chan queryResult)
82 p.queries <- queryRequest{
83 query: metadataQuery{prom: p, ctx: ctx, metric: metric, timestamp: time.Now()},
84 result: resultChan,
85 }
86
87 result := <-resultChan
88 if result.err != nil {
89 return nil, QueryError{err: result.err, msg: decodeError(result.err)}
90 }
91
92 metadata := MetadataResult{URI: p.safeURI, Metadata: result.value.(map[string][]v1.Metadata)[metric]}
93
94 return &metadata, nil
95}
96
97func streamMetadata(r io.Reader) (meta map[string][]v1.Metadata, err error) {
98 defer dummyReadAll(r)
99
100 var status, errType, errText string
101 meta = map[string][]v1.Metadata{}
102 decoder := current.Object(
103 current.Key("status", current.Value(func(s string, isNil bool) {
104 status = s
105 })),
106 current.Key("error", current.Value(func(s string, isNil bool) {
107 errText = s
108 })),
109 current.Key("errorType", current.Value(func(s string, isNil bool) {
110 errType = s
111 })),
112 current.Key("data", current.Map(func(k string, v []v1.Metadata) {
113 meta[k] = v
114 })),
115 )
116
117 dec := json.NewDecoder(r)
118 if err = decoder.Stream(dec); err != nil {
119 return nil, APIError{Status: status, ErrorType: v1.ErrBadResponse, Err: fmt.Sprintf("JSON parse error: %s", err)}
120 }
121
122 if status != "success" {
123 return nil, APIError{Status: status, ErrorType: decodeErrorType(errType), Err: errText}
124 }
125
126 return meta, nil
127}
128