gauge.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package prometheus
  2. import (
  3. "context"
  4. "fmt"
  5. "strings"
  6. "sync"
  7. "time"
  8. "github.com/prometheus/common/model"
  9. )
  10. type Gauge struct {
  11. wg *sync.WaitGroup
  12. name string
  13. labels map[string]string
  14. rangeSelector string
  15. baseTime time.Time
  16. minutes int64
  17. }
  18. func NewGauge(wg *sync.WaitGroup, name string, labels map[string]string, ts time.Time, mins int64) Gauge {
  19. rangeSelector := fmt.Sprintf("%dm", mins)
  20. return Gauge{
  21. wg: wg,
  22. name: name,
  23. labels: labels,
  24. rangeSelector: rangeSelector,
  25. baseTime: ts,
  26. minutes: mins,
  27. }
  28. }
  29. func (g Gauge) makeMetricNameLabels(name string) string {
  30. labelList := make([]string, 0, len(g.labels))
  31. for key, val := range g.labels {
  32. labelList = append(labelList, fmt.Sprintf("%s='%s'", key, val))
  33. }
  34. return fmt.Sprintf("%s{%s}", name, strings.Join(labelList, ","))
  35. }
  36. func (g Gauge) Max(res *float64) error {
  37. defer g.wg.Done()
  38. nameLabels := g.makeMetricNameLabels(g.name)
  39. query := fmt.Sprintf("max(max_over_time(%s[%s]))", nameLabels, g.rangeSelector)
  40. result, _, err := PromeApi().Query(context.Background(), query, g.baseTime)
  41. if err != nil {
  42. return err
  43. }
  44. for _, sample := range result.(model.Vector) {
  45. *res = float64(sample.Value)
  46. }
  47. return nil
  48. }