cloudflare/pint

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v0.11.1

Branches

Tags

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

Clone

HTTPS

Download ZIP

internal/promapi/query.go

72lines · modecode

1package promapi
2
3import (
4 "context"
5 "fmt"
6 "time"
7
8 "github.com/prometheus/common/model"
9 "github.com/rs/zerolog/log"
10)
11
12type QueryResult struct {
13 Series model.Vector
14 DurationSeconds float64
15}
16
17func (p *Prometheus) Query(ctx context.Context, expr string) (*QueryResult, error) {
18 log.Debug().Str("uri", p.uri).Str("query", expr).Msg("Scheduling prometheus query")
19
20 lockKey := expr
21 p.lock.lock(lockKey)
22 defer p.lock.unlock((lockKey))
23
24 if v, ok := p.cache.Get(expr); ok {
25 log.Debug().Str("key", expr).Str("uri", p.uri).Msg("Query cache hit")
26 r := v.(QueryResult)
27 return &r, nil
28 }
29
30 log.Debug().Str("uri", p.uri).Str("query", expr).Msg("Query started")
31
32 ctx, cancel := context.WithTimeout(ctx, p.timeout)
33 defer cancel()
34
35 prometheusQueriesTotal.WithLabelValues(p.name, "/api/v1/query").Inc()
36 start := time.Now()
37 result, _, err := p.api.Query(ctx, expr, start)
38 duration := time.Since(start)
39 log.Debug().
40 Str("uri", p.uri).
41 Str("query", expr).
42 Str("duration", HumanizeDuration(duration)).
43 Msg("Query completed")
44 if err != nil {
45 log.Error().Err(err).
46 Str("uri", p.uri).
47 Str("query", expr).
48 Msg("Query failed")
49 prometheusQueryErrorsTotal.WithLabelValues(p.name, "/api/v1/query", errReason(err)).Inc()
50 return nil, err
51 }
52
53 qr := QueryResult{
54 DurationSeconds: duration.Seconds(),
55 }
56
57 switch result.Type() {
58 case model.ValVector:
59 vectorVal := result.(model.Vector)
60 qr.Series = vectorVal
61 default:
62 log.Error().Str("uri", p.uri).Str("query", expr).Msgf("Query returned unknown result type: %v", result.Type())
63 prometheusQueryErrorsTotal.WithLabelValues(p.name, "/api/v1/query", "unknown result type").Inc()
64 return nil, fmt.Errorf("unknown result type: %v", result.Type())
65 }
66 log.Debug().Str("uri", p.uri).Str("query", expr).Int("series", len(qr.Series)).Msg("Parsed response")
67
68 log.Debug().Str("key", expr).Str("uri", p.uri).Msg("Query cache miss")
69 p.cache.Add(expr, qr)
70
71 return &qr, nil
72}
73