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