helpers.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package prom
  2. import (
  3. "context"
  4. "fmt"
  5. "strings"
  6. "time"
  7. prometheus "github.com/prometheus/client_golang/api"
  8. v1 "github.com/prometheus/client_golang/api/prometheus/v1"
  9. "gopkg.in/yaml.v2"
  10. )
  11. const PrometheusTroubleshootingURL = "https://www.opencost.io/docs/integrations/prometheus"
  12. // ScrapeConfig is the minimalized view of a prometheus scrape configuration
  13. type ScrapeConfig struct {
  14. JobName string `yaml:"job_name,omitempty"`
  15. ScrapeInterval string `yaml:"scrape_interval,omitempty"`
  16. }
  17. // PrometheusConfig is the minimalized view of a prometheus configuration
  18. type PrometheusConfig struct {
  19. ScrapeConfigs []ScrapeConfig `yaml:"scrape_configs,omitempty"`
  20. }
  21. // GetPrometheusConfig uses the provided yaml string to parse the minimalized prometheus config
  22. func GetPrometheusConfig(pcfg string) (PrometheusConfig, error) {
  23. var promCfg PrometheusConfig
  24. err := yaml.Unmarshal([]byte(pcfg), &promCfg)
  25. return promCfg, err
  26. }
  27. // ScrapeIntervalFor uses the provided prometheus client to locate a scrape interval for a specific job name
  28. func ScrapeIntervalFor(client prometheus.Client, jobName string) (time.Duration, error) {
  29. api := v1.NewAPI(client)
  30. promConfig, err := api.Config(context.Background())
  31. if err != nil {
  32. return 0, err
  33. }
  34. cfg, err := GetPrometheusConfig(promConfig.YAML)
  35. if err != nil {
  36. return 0, err
  37. }
  38. for _, sc := range cfg.ScrapeConfigs {
  39. if strings.EqualFold(sc.JobName, jobName) {
  40. if sc.ScrapeInterval != "" {
  41. si := sc.ScrapeInterval
  42. sid, err := time.ParseDuration(si)
  43. if err != nil {
  44. return 0, fmt.Errorf("Error parsing scrape config for %s", sc.JobName)
  45. }
  46. return sid, nil
  47. }
  48. }
  49. }
  50. return 0, fmt.Errorf("Failed to locate scrape config for %s", jobName)
  51. }