helpers.go 1.7 KB

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