cloudflare/pint
Publicmirrored from https://github.com/cloudflare/pintAvailable
internal/promapi/config.go
67lines · modecode
| 1 | package promapi |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | "time" |
| 7 | |
| 8 | "github.com/rs/zerolog/log" |
| 9 | "gopkg.in/yaml.v3" |
| 10 | ) |
| 11 | |
| 12 | type ConfigSectionGlobal struct { |
| 13 | ScrapeInterval time.Duration `yaml:"scrape_interval"` |
| 14 | ScrapeTimeout time.Duration `yaml:"scrape_timeout"` |
| 15 | EvaluationInterval time.Duration `yaml:"evaluation_interval"` |
| 16 | ExternalLabels map[string]string `yaml:"external_labels"` |
| 17 | } |
| 18 | |
| 19 | type PrometheusConfig struct { |
| 20 | Global ConfigSectionGlobal `yaml:"global"` |
| 21 | } |
| 22 | |
| 23 | func (p *Prometheus) Config(ctx context.Context) (*PrometheusConfig, error) { |
| 24 | log.Debug().Str("uri", p.uri).Msg("Query Prometheus configuration") |
| 25 | |
| 26 | key := "/api/v1/status/config" |
| 27 | p.lock.lock(key) |
| 28 | defer p.lock.unlock((key)) |
| 29 | |
| 30 | if v, ok := p.cache.Get(key); ok { |
| 31 | log.Debug().Str("key", key).Str("uri", p.uri).Msg("Config cache hit") |
| 32 | cfg := v.(PrometheusConfig) |
| 33 | return &cfg, nil |
| 34 | } |
| 35 | |
| 36 | ctx, cancel := context.WithTimeout(ctx, p.timeout) |
| 37 | defer cancel() |
| 38 | |
| 39 | prometheusQueriesTotal.WithLabelValues(p.name, "/api/v1/status/config") |
| 40 | resp, err := p.api.Config(ctx) |
| 41 | if err != nil { |
| 42 | log.Error().Err(err).Str("uri", p.uri).Msg("Failed to query Prometheus configuration") |
| 43 | prometheusQueryErrorsTotal.WithLabelValues(p.name, "/api/v1/status/config", errReason(err)).Inc() |
| 44 | return nil, fmt.Errorf("failed to query Prometheus config: %w", err) |
| 45 | } |
| 46 | |
| 47 | var cfg PrometheusConfig |
| 48 | if err = yaml.Unmarshal([]byte(resp.YAML), &cfg); err != nil { |
| 49 | prometheusQueryErrorsTotal.WithLabelValues(p.name, "/api/v1/status/config", errReason(err)).Inc() |
| 50 | return nil, fmt.Errorf("failed to decode config data in %s response: %w", p.uri, err) |
| 51 | } |
| 52 | |
| 53 | if cfg.Global.ScrapeInterval == 0 { |
| 54 | cfg.Global.ScrapeInterval = time.Minute |
| 55 | } |
| 56 | if cfg.Global.ScrapeTimeout == 0 { |
| 57 | cfg.Global.ScrapeTimeout = time.Second * 10 |
| 58 | } |
| 59 | if cfg.Global.EvaluationInterval == 0 { |
| 60 | cfg.Global.EvaluationInterval = time.Minute |
| 61 | } |
| 62 | |
| 63 | log.Debug().Str("key", key).Str("uri", p.uri).Msg("Config cache miss") |
| 64 | p.cache.Add(key, cfg) |
| 65 | |
| 66 | return &cfg, nil |
| 67 | } |
| 68 | |