cloudflare/pint
Publicmirrored from https://github.com/cloudflare/pintAvailable
internal/promapi/query.go
76lines · modecode
| 1 | package promapi |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | "sync" |
| 7 | "time" |
| 8 | |
| 9 | "github.com/cloudflare/pint/internal/keylock" |
| 10 | |
| 11 | "github.com/prometheus/client_golang/api" |
| 12 | v1 "github.com/prometheus/client_golang/api/prometheus/v1" |
| 13 | "github.com/prometheus/common/model" |
| 14 | "github.com/rs/zerolog/log" |
| 15 | ) |
| 16 | |
| 17 | var km = keylock.NewPartitionLocker((&sync.Mutex{})) |
| 18 | |
| 19 | type QueryResult struct { |
| 20 | Series model.Vector |
| 21 | DurationSeconds float64 |
| 22 | } |
| 23 | |
| 24 | func Query(uri string, timeout time.Duration, expr string, lockKey *string) (*QueryResult, error) { |
| 25 | log.Debug().Str("uri", uri).Str("query", expr).Msg("Scheduling prometheus query") |
| 26 | key := uri |
| 27 | if lockKey != nil { |
| 28 | key = *lockKey |
| 29 | } |
| 30 | km.Lock(key) |
| 31 | defer km.Unlock((key)) |
| 32 | |
| 33 | log.Debug().Str("uri", uri).Str("query", expr).Msg("Query started") |
| 34 | |
| 35 | client, err := api.NewClient(api.Config{Address: uri}) |
| 36 | if err != nil { |
| 37 | log.Error().Err(err).Msg("Failed to setup new Prometheus API client") |
| 38 | return nil, err |
| 39 | } |
| 40 | |
| 41 | v1api := v1.NewAPI(client) |
| 42 | ctx, cancel := context.WithTimeout(context.Background(), timeout) |
| 43 | defer cancel() |
| 44 | |
| 45 | start := time.Now() |
| 46 | result, _, err := v1api.Query(ctx, expr, start) |
| 47 | duration := time.Since(start) |
| 48 | log.Debug(). |
| 49 | Str("uri", uri). |
| 50 | Str("query", expr). |
| 51 | Str("duration", HumanizeDuration(duration)). |
| 52 | Msg("Query completed") |
| 53 | if err != nil { |
| 54 | log.Error().Err(err). |
| 55 | Str("uri", uri). |
| 56 | Str("query", expr). |
| 57 | Msg("Query failed") |
| 58 | return nil, err |
| 59 | } |
| 60 | |
| 61 | qr := QueryResult{ |
| 62 | DurationSeconds: duration.Seconds(), |
| 63 | } |
| 64 | |
| 65 | switch result.Type() { |
| 66 | case model.ValVector: |
| 67 | vectorVal := result.(model.Vector) |
| 68 | qr.Series = vectorVal |
| 69 | default: |
| 70 | log.Error().Err(err).Str("uri", uri).Str("query", expr).Msgf("Query returned unknown result type: %v", result) |
| 71 | return nil, fmt.Errorf("unknown result type: %v", result) |
| 72 | } |
| 73 | log.Debug().Str("uri", uri).Str("query", expr).Int("series", len(qr.Series)).Msg("Parsed response") |
| 74 | |
| 75 | return &qr, nil |
| 76 | } |
| 77 | |