cloudflare/pint

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v0.28.1

Branches

Tags

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

Clone

HTTPS

Download ZIP

internal/promapi/metadata.go

81lines · modecode

1package promapi
2
3import (
4 "context"
5 "crypto/sha1"
6 "fmt"
7 "io"
8 "time"
9
10 v1 "github.com/prometheus/client_golang/api/prometheus/v1"
11 "github.com/rs/zerolog/log"
12)
13
14type MetadataResult struct {
15 URI string
16 Metadata []v1.Metadata
17}
18
19type metadataQuery struct {
20 prom *Prometheus
21 ctx context.Context
22 metric string
23 timestamp time.Time
24}
25
26func (q metadataQuery) Run() (any, error) {
27 log.Debug().
28 Str("uri", q.prom.uri).
29 Str("metric", q.metric).
30 Msg("Getting prometheus metrics metadata")
31
32 ctx, cancel := context.WithTimeout(q.ctx, q.prom.timeout)
33 defer cancel()
34
35 v, err := q.prom.api.Metadata(ctx, q.metric, "")
36 if err != nil {
37 return nil, fmt.Errorf("failed to query Prometheus metrics metadata: %w", err)
38 }
39 return v, nil
40}
41
42func (q metadataQuery) Endpoint() string {
43 return "/api/v1/metadata"
44}
45
46func (q metadataQuery) String() string {
47 return q.metric
48}
49
50func (q metadataQuery) CacheKey() string {
51 h := sha1.New()
52 _, _ = io.WriteString(h, q.Endpoint())
53 _, _ = io.WriteString(h, "\n")
54 _, _ = io.WriteString(h, q.metric)
55 _, _ = io.WriteString(h, "\n")
56 _, _ = io.WriteString(h, q.timestamp.Round(cacheExpiry).Format(time.RFC3339))
57 return fmt.Sprintf("%x", h.Sum(nil))
58}
59
60func (p *Prometheus) Metadata(ctx context.Context, metric string) (*MetadataResult, error) {
61 log.Debug().Str("uri", p.uri).Str("metric", metric).Msg("Scheduling Prometheus metrics metadata query")
62
63 key := fmt.Sprintf("/api/v1/metadata/%s", metric)
64 p.locker.lock(key)
65 defer p.locker.unlock(key)
66
67 resultChan := make(chan queryResult)
68 p.queries <- queryRequest{
69 query: metadataQuery{prom: p, ctx: ctx, metric: metric, timestamp: time.Now()},
70 result: resultChan,
71 }
72
73 result := <-resultChan
74 if result.err != nil {
75 return nil, QueryError{err: result.err, msg: decodeError(result.err)}
76 }
77
78 metadata := MetadataResult{URI: p.uri, Metadata: result.value.(map[string][]v1.Metadata)[metric]}
79
80 return &metadata, nil
81}
82