uptime.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package aggregator
  2. import (
  3. "sync"
  4. "time"
  5. )
  6. // uptimeAggregator is a MetricAggregator which records the first and last timestamp of updates called on it
  7. type uptimeAggregator struct {
  8. lock sync.Mutex
  9. labelValues []string
  10. start *time.Time
  11. end *time.Time
  12. }
  13. func Uptime(labelValues []string) MetricAggregator {
  14. return &uptimeAggregator{
  15. labelValues: labelValues,
  16. }
  17. }
  18. func (a *uptimeAggregator) AdditionInfo() map[string]string {
  19. return nil
  20. }
  21. func (a *uptimeAggregator) LabelValues() []string {
  22. return a.labelValues
  23. }
  24. func (a *uptimeAggregator) Update(value float64, timestamp time.Time, additionalInfo map[string]string) {
  25. a.lock.Lock()
  26. defer a.lock.Unlock()
  27. if a.start == nil {
  28. a.start = &timestamp
  29. return
  30. }
  31. if timestamp.After(*a.start) {
  32. a.end = &timestamp
  33. }
  34. }
  35. func (a *uptimeAggregator) Value() []MetricValue {
  36. a.lock.Lock()
  37. defer a.lock.Unlock()
  38. metricValues := make([]MetricValue, 0)
  39. if a.start != nil {
  40. metricValues = append(metricValues, MetricValue{Value: 1, Timestamp: a.start})
  41. }
  42. if a.end != nil {
  43. metricValues = append(metricValues, MetricValue{Value: 1, Timestamp: a.end})
  44. }
  45. return metricValues
  46. }