cloudflare/pint
Publicmirrored from https://github.com/cloudflare/pintAvailable
internal/promapi/metadata.go
47lines · modecode
| 1 | package promapi |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | |
| 7 | v1 "github.com/prometheus/client_golang/api/prometheus/v1" |
| 8 | "github.com/rs/zerolog/log" |
| 9 | ) |
| 10 | |
| 11 | type MetadataResult struct { |
| 12 | URI string |
| 13 | Metadata []v1.Metadata |
| 14 | } |
| 15 | |
| 16 | func (p *Prometheus) Metadata(ctx context.Context, metric string) (*MetadataResult, error) { |
| 17 | log.Debug().Str("uri", p.uri).Str("metric", metric).Msg("Query Prometheus metric metadata") |
| 18 | |
| 19 | key := fmt.Sprintf("/api/v1/metadata/%s", metric) |
| 20 | p.lock.lock(key) |
| 21 | defer p.lock.unlock((key)) |
| 22 | |
| 23 | if v, ok := p.cache.Get(key); ok { |
| 24 | log.Debug().Str("key", key).Str("uri", p.uri).Str("metric", metric).Msg("Metric metadata cache hit") |
| 25 | prometheusCacheHitsTotal.WithLabelValues(p.name, "/api/v1/metadata").Inc() |
| 26 | metadata := v.(MetadataResult) |
| 27 | return &metadata, nil |
| 28 | } |
| 29 | |
| 30 | ctx, cancel := context.WithTimeout(ctx, p.timeout) |
| 31 | defer cancel() |
| 32 | |
| 33 | prometheusQueriesTotal.WithLabelValues(p.name, "/api/v1/metadata").Inc() |
| 34 | resp, err := p.api.Metadata(ctx, metric, "") |
| 35 | if err != nil { |
| 36 | log.Error().Err(err).Str("uri", p.uri).Msg("Failed to query Prometheus metric metadata") |
| 37 | prometheusQueryErrorsTotal.WithLabelValues(p.name, "/api/v1/metadata", errReason(err)).Inc() |
| 38 | return nil, fmt.Errorf("failed to query Prometheus metric metadata: %w", err) |
| 39 | } |
| 40 | |
| 41 | metadata := MetadataResult{URI: p.uri, Metadata: resp[metric]} |
| 42 | |
| 43 | log.Debug().Str("key", key).Str("uri", p.uri).Str("metric", metric).Msg("Metric metadata cache miss") |
| 44 | p.cache.Add(key, metadata) |
| 45 | |
| 46 | return &metadata, nil |
| 47 | } |
| 48 | |