aggregator.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. // ToVector converts the MetricValue into a util.Vector (adapter for source.QueryResults).
  13. func (mv *MetricValue) ToVector() *util.Vector {
  14. timestamp := 0.0
  15. if mv.Timestamp != nil {
  16. timestamp = float64(mv.Timestamp.Unix())
  17. }
  18. return &util.Vector{
  19. Timestamp: timestamp,
  20. Value: mv.Value,
  21. }
  22. }
  23. // MetricResult contains the metric result labels and label values, and a slice of
  24. // MetricValues.
  25. type MetricResult struct {
  26. MetricLabels map[string]string
  27. Values []MetricValue
  28. }
  29. // ToQueryResult converts the MetricResult into a source.QueryResult, which is the format used by
  30. // the data source to return query results.
  31. func (mr *MetricResult) ToQueryResult() *source.QueryResult {
  32. metrics := make(map[string]any, len(mr.MetricLabels))
  33. for key, value := range mr.MetricLabels {
  34. metrics[key] = value
  35. }
  36. values := make([]*util.Vector, len(mr.Values))
  37. for i, value := range mr.Values {
  38. values[i] = value.ToVector()
  39. }
  40. return source.NewQueryResult(metrics, values, nil)
  41. }
  42. // MetricAggregator is an interface that defines the methods for a metric metric aggregation.
  43. // For example, we have a metric `foo_metric`, and we wish to query and collect the average over time.
  44. // In this case, the `AverageOverTime` component is the MetricAggregator. It is the component responsible
  45. // for routing updates to metric values into their proper condensed form.
  46. type MetricAggregator interface {
  47. AdditionInfo() map[string]string
  48. Update(value float64, timestamp time.Time, additionalInfo map[string]string)
  49. Value() []MetricValue
  50. LabelValues() []string
  51. }
  52. // MetricAggregatorFactory is a function that accepts a string name and returns a pointer to a MetricAggregator
  53. // implementation.
  54. type MetricAggregatorFactory func(labelValues []string) MetricAggregator