cloudflare/pint

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v0.13.1

Branches

Tags

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

Clone

HTTPS

Download ZIP

internal/promapi/query.go

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