cloudflare/pint
Publicmirrored from https://github.com/cloudflare/pintAvailable
internal/promapi/query.go
83lines · modecode
| 1 | package promapi |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/sha1" |
| 6 | "fmt" |
| 7 | "io" |
| 8 | "time" |
| 9 | |
| 10 | "github.com/prometheus/common/model" |
| 11 | "github.com/rs/zerolog/log" |
| 12 | ) |
| 13 | |
| 14 | type QueryResult struct { |
| 15 | URI string |
| 16 | Series model.Vector |
| 17 | DurationSeconds float64 |
| 18 | } |
| 19 | |
| 20 | type instantQuery struct { |
| 21 | prom *Prometheus |
| 22 | ctx context.Context |
| 23 | expr string |
| 24 | } |
| 25 | |
| 26 | func (q instantQuery) Run() (any, error) { |
| 27 | log.Debug(). |
| 28 | Str("uri", q.prom.uri). |
| 29 | Str("query", q.expr). |
| 30 | Msg("Running prometheus query") |
| 31 | |
| 32 | ctx, cancel := context.WithTimeout(q.ctx, q.prom.timeout) |
| 33 | defer cancel() |
| 34 | |
| 35 | v, _, err := q.prom.api.Query(ctx, q.expr, time.Now()) |
| 36 | return v, err |
| 37 | } |
| 38 | |
| 39 | func (q instantQuery) Endpoint() string { |
| 40 | return "/api/v1/query" |
| 41 | } |
| 42 | |
| 43 | func (q instantQuery) String() string { |
| 44 | return q.expr |
| 45 | } |
| 46 | |
| 47 | func (q instantQuery) CacheKey() string { |
| 48 | h := sha1.New() |
| 49 | _, _ = io.WriteString(h, q.Endpoint()) |
| 50 | _, _ = io.WriteString(h, "\n") |
| 51 | _, _ = io.WriteString(h, q.expr) |
| 52 | return fmt.Sprintf("%x", h.Sum(nil)) |
| 53 | } |
| 54 | |
| 55 | func (p *Prometheus) Query(ctx context.Context, expr string) (*QueryResult, error) { |
| 56 | log.Debug().Str("uri", p.uri).Str("query", expr).Msg("Scheduling prometheus query") |
| 57 | |
| 58 | resultChan := make(chan queryResult) |
| 59 | p.queries <- queryRequest{ |
| 60 | query: instantQuery{prom: p, ctx: ctx, expr: expr}, |
| 61 | result: resultChan, |
| 62 | } |
| 63 | |
| 64 | result := <-resultChan |
| 65 | if result.err != nil { |
| 66 | return nil, QueryError{err: result.err, msg: decodeError(result.err)} |
| 67 | } |
| 68 | |
| 69 | qr := QueryResult{URI: p.uri} |
| 70 | |
| 71 | switch result.value.(model.Value).Type() { |
| 72 | case model.ValVector: |
| 73 | vectorVal := result.value.(model.Vector) |
| 74 | qr.Series = vectorVal |
| 75 | default: |
| 76 | log.Error().Str("uri", p.uri).Str("query", expr).Msgf("Query returned unknown result type: %v", result.value.(model.Value).Type()) |
| 77 | prometheusQueryErrorsTotal.WithLabelValues(p.name, "/api/v1/query", "unknown result type").Inc() |
| 78 | return nil, fmt.Errorf("unknown result type: %v", result.value.(model.Value).Type()) |
| 79 | } |
| 80 | log.Debug().Str("uri", p.uri).Str("query", expr).Int("series", len(qr.Series)).Msg("Parsed response") |
| 81 | |
| 82 | return &qr, nil |
| 83 | } |
| 84 | |