aggregator.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package aggregator
  2. import (
  3. "time"
  4. "github.com/opencost/opencost/core/pkg/source"
  5. "github.com/opencost/opencost/core/pkg/util"
  6. )
  7. // MetricValue is a resulting data point value with an optional timestamp.
  8. type MetricValue struct {
  9. Value float64
  10. Timestamp *time.Time
  11. }
  12. // MetricResult contains a resulting metric name, the associated labels and label values, and a slice of
  13. // MetricValues.
  14. type MetricResult struct {
  15. Name string
  16. MetricLabels map[string]string
  17. Values []MetricValue
  18. }
  19. func (mr *MetricResult) ToQueryResult() *source.QueryResult {
  20. metrics := map[string]any{}
  21. for key, value := range mr.MetricLabels {
  22. metrics[key] = value
  23. }
  24. values := make([]*util.Vector, len(mr.Values))
  25. for i, value := range mr.Values {
  26. timestamp := 0.0
  27. if value.Timestamp != nil {
  28. timestamp = float64(value.Timestamp.Unix())
  29. }
  30. values[i] = &util.Vector{
  31. Timestamp: timestamp,
  32. Value: value.Value,
  33. }
  34. }
  35. return source.NewQueryResult(metrics, values, nil)
  36. }
  37. // MetricAggregator is an interface that defines the methods for a metric metric aggregation.
  38. // For example, we have a metric `foo_metric`, and we wish to query and collect the average over time.
  39. // In this case, the `AverageOverTime` component is the MetricAggregator. It is the component responsible
  40. // for routing updates to metric values into their proper condensed form.
  41. type MetricAggregator interface {
  42. Name() string
  43. AdditionInfo() map[string]string
  44. Update(value float64, timestamp time.Time, additionalInfo map[string]string)
  45. Value() []MetricValue
  46. LabelValues() []string
  47. }
  48. // MetricAggregatorFactory is a function that accepts a string name and returns a pointer to a MetricAggregator
  49. // implementation.
  50. type MetricAggregatorFactory func(name string, labelValues []string) MetricAggregator