cloudflare/pint
Publicmirrored from https://github.com/cloudflare/pintAvailable
internal/promapi/config.go
75lines · 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 | type ConfigResult struct { |
| 24 | URI string |
| 25 | Config PrometheusConfig |
| 26 | } |
| 27 | |
| 28 | func (p *Prometheus) Config(ctx context.Context) (*ConfigResult, error) { |
| 29 | log.Debug().Str("uri", p.uri).Msg("Query Prometheus configuration") |
| 30 | |
| 31 | key := "/api/v1/status/config" |
| 32 | p.lock.lock(key) |
| 33 | defer p.lock.unlock((key)) |
| 34 | |
| 35 | if v, ok := p.cache.Get(key); ok { |
| 36 | log.Debug().Str("key", key).Str("uri", p.uri).Msg("Config cache hit") |
| 37 | prometheusCacheHitsTotal.WithLabelValues(p.name, "/api/v1/status/config") |
| 38 | cfg := v.(ConfigResult) |
| 39 | return &cfg, nil |
| 40 | } |
| 41 | |
| 42 | ctx, cancel := context.WithTimeout(ctx, p.timeout) |
| 43 | defer cancel() |
| 44 | |
| 45 | prometheusQueriesTotal.WithLabelValues(p.name, "/api/v1/status/config") |
| 46 | resp, err := p.api.Config(ctx) |
| 47 | if err != nil { |
| 48 | log.Error().Err(err).Str("uri", p.uri).Msg("Failed to query Prometheus configuration") |
| 49 | prometheusQueryErrorsTotal.WithLabelValues(p.name, "/api/v1/status/config", errReason(err)).Inc() |
| 50 | return nil, fmt.Errorf("failed to query Prometheus config: %w", err) |
| 51 | } |
| 52 | |
| 53 | var cfg PrometheusConfig |
| 54 | if err = yaml.Unmarshal([]byte(resp.YAML), &cfg); err != nil { |
| 55 | prometheusQueryErrorsTotal.WithLabelValues(p.name, "/api/v1/status/config", errReason(err)).Inc() |
| 56 | return nil, fmt.Errorf("failed to decode config data in %s response: %w", p.uri, err) |
| 57 | } |
| 58 | |
| 59 | if cfg.Global.ScrapeInterval == 0 { |
| 60 | cfg.Global.ScrapeInterval = time.Minute |
| 61 | } |
| 62 | if cfg.Global.ScrapeTimeout == 0 { |
| 63 | cfg.Global.ScrapeTimeout = time.Second * 10 |
| 64 | } |
| 65 | if cfg.Global.EvaluationInterval == 0 { |
| 66 | cfg.Global.EvaluationInterval = time.Minute |
| 67 | } |
| 68 | |
| 69 | r := ConfigResult{URI: p.uri, Config: cfg} |
| 70 | |
| 71 | log.Debug().Str("key", key).Str("uri", p.uri).Msg("Config cache miss") |
| 72 | p.cache.Add(key, r) |
| 73 | |
| 74 | return &r, nil |
| 75 | } |