cloudflare/pint
Publicmirrored from https://github.com/cloudflare/pintAvailable
internal/promapi/flags.go
77lines · modecode
| 1 | package promapi |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/sha1" |
| 6 | "fmt" |
| 7 | "io" |
| 8 | "time" |
| 9 | |
| 10 | v1 "github.com/prometheus/client_golang/api/prometheus/v1" |
| 11 | "github.com/rs/zerolog/log" |
| 12 | ) |
| 13 | |
| 14 | type FlagsResult struct { |
| 15 | URI string |
| 16 | Flags v1.FlagsResult |
| 17 | } |
| 18 | |
| 19 | type flagsQuery struct { |
| 20 | prom *Prometheus |
| 21 | ctx context.Context |
| 22 | timestamp time.Time |
| 23 | } |
| 24 | |
| 25 | func (q flagsQuery) Run() (any, error) { |
| 26 | log.Debug(). |
| 27 | Str("uri", q.prom.uri). |
| 28 | Msg("Getting prometheus flags") |
| 29 | |
| 30 | ctx, cancel := context.WithTimeout(q.ctx, q.prom.timeout) |
| 31 | defer cancel() |
| 32 | |
| 33 | v, err := q.prom.api.Flags(ctx) |
| 34 | if err != nil { |
| 35 | return nil, fmt.Errorf("failed to query Prometheus flags: %w", err) |
| 36 | } |
| 37 | return v, nil |
| 38 | } |
| 39 | |
| 40 | func (q flagsQuery) Endpoint() string { |
| 41 | return "/api/v1/status/flags" |
| 42 | } |
| 43 | |
| 44 | func (q flagsQuery) String() string { |
| 45 | return "/api/v1/status/flags" |
| 46 | } |
| 47 | |
| 48 | func (q flagsQuery) CacheKey() string { |
| 49 | h := sha1.New() |
| 50 | _, _ = io.WriteString(h, q.Endpoint()) |
| 51 | _, _ = io.WriteString(h, "\n") |
| 52 | _, _ = io.WriteString(h, q.timestamp.Round(cacheExpiry).Format(time.RFC3339)) |
| 53 | return fmt.Sprintf("%x", h.Sum(nil)) |
| 54 | } |
| 55 | |
| 56 | func (p *Prometheus) Flags(ctx context.Context) (*FlagsResult, error) { |
| 57 | log.Debug().Str("uri", p.uri).Msg("Scheduling Prometheus flags query") |
| 58 | |
| 59 | key := "/api/v1/status/flags" |
| 60 | p.locker.lock(key) |
| 61 | defer p.locker.unlock(key) |
| 62 | |
| 63 | resultChan := make(chan queryResult) |
| 64 | p.queries <- queryRequest{ |
| 65 | query: flagsQuery{prom: p, ctx: ctx, timestamp: time.Now()}, |
| 66 | result: resultChan, |
| 67 | } |
| 68 | |
| 69 | result := <-resultChan |
| 70 | if result.err != nil { |
| 71 | return nil, QueryError{err: result.err, msg: decodeError(result.err)} |
| 72 | } |
| 73 | |
| 74 | r := FlagsResult{URI: p.uri, Flags: result.value.(v1.FlagsResult)} |
| 75 | |
| 76 | return &r, nil |
| 77 | } |