cloudflare/pint

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v0.15.1

Branches

Tags

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

Clone

HTTPS

Download ZIP

internal/promapi/query.go

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