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