cloudflare/pint
Publicmirrored from https://github.com/cloudflare/pintAvailable
internal/promapi/query.go
69lines · 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 | |
| 12 | type QueryResult struct { |
| 13 | Series model.Vector |
| 14 | DurationSeconds float64 |
| 15 | } |
| 16 | |
| 17 | func (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 | start := time.Now() |
| 36 | result, _, err := p.api.Query(ctx, expr, start) |
| 37 | duration := time.Since(start) |
| 38 | log.Debug(). |
| 39 | Str("uri", p.uri). |
| 40 | Str("query", expr). |
| 41 | Str("duration", HumanizeDuration(duration)). |
| 42 | Msg("Query completed") |
| 43 | if err != nil { |
| 44 | log.Error().Err(err). |
| 45 | Str("uri", p.uri). |
| 46 | Str("query", expr). |
| 47 | Msg("Query failed") |
| 48 | return nil, err |
| 49 | } |
| 50 | |
| 51 | qr := QueryResult{ |
| 52 | DurationSeconds: duration.Seconds(), |
| 53 | } |
| 54 | |
| 55 | switch result.Type() { |
| 56 | case model.ValVector: |
| 57 | vectorVal := result.(model.Vector) |
| 58 | qr.Series = vectorVal |
| 59 | default: |
| 60 | log.Error().Err(err).Str("uri", p.uri).Str("query", expr).Msgf("Query returned unknown result type: %v", result.Type()) |
| 61 | return nil, fmt.Errorf("unknown result type: %v", result.Type()) |
| 62 | } |
| 63 | log.Debug().Str("uri", p.uri).Str("query", expr).Int("series", len(qr.Series)).Msg("Parsed response") |
| 64 | |
| 65 | log.Debug().Str("key", expr).Str("uri", p.uri).Msg("Query cache miss") |
| 66 | p.cache.Add(expr, qr) |
| 67 | |
| 68 | return &qr, nil |
| 69 | } |
| 70 | |