inmem.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. package metrics
  2. import (
  3. "bytes"
  4. "fmt"
  5. "math"
  6. "net/url"
  7. "strings"
  8. "sync"
  9. "time"
  10. )
  11. var spaceReplacer = strings.NewReplacer(" ", "_")
  12. // InmemSink provides a MetricSink that does in-memory aggregation
  13. // without sending metrics over a network. It can be embedded within
  14. // an application to provide profiling information.
  15. type InmemSink struct {
  16. // How long is each aggregation interval
  17. interval time.Duration
  18. // Retain controls how many metrics interval we keep
  19. retain time.Duration
  20. // maxIntervals is the maximum length of intervals.
  21. // It is retain / interval.
  22. maxIntervals int
  23. // intervals is a slice of the retained intervals
  24. intervals []*IntervalMetrics
  25. intervalLock sync.RWMutex
  26. rateDenom float64
  27. }
  28. // IntervalMetrics stores the aggregated metrics
  29. // for a specific interval
  30. type IntervalMetrics struct {
  31. sync.RWMutex
  32. // The start time of the interval
  33. Interval time.Time
  34. // Gauges maps the key to the last set value
  35. Gauges map[string]GaugeValue
  36. // Points maps the string to the list of emitted values
  37. // from EmitKey
  38. Points map[string][]float32
  39. // Counters maps the string key to a sum of the counter
  40. // values
  41. Counters map[string]SampledValue
  42. // Samples maps the key to an AggregateSample,
  43. // which has the rolled up view of a sample
  44. Samples map[string]SampledValue
  45. // done is closed when this interval has ended, and a new IntervalMetrics
  46. // has been created to receive any future metrics.
  47. done chan struct{}
  48. }
  49. // NewIntervalMetrics creates a new IntervalMetrics for a given interval
  50. func NewIntervalMetrics(intv time.Time) *IntervalMetrics {
  51. return &IntervalMetrics{
  52. Interval: intv,
  53. Gauges: make(map[string]GaugeValue),
  54. Points: make(map[string][]float32),
  55. Counters: make(map[string]SampledValue),
  56. Samples: make(map[string]SampledValue),
  57. done: make(chan struct{}),
  58. }
  59. }
  60. // AggregateSample is used to hold aggregate metrics
  61. // about a sample
  62. type AggregateSample struct {
  63. Count int // The count of emitted pairs
  64. Rate float64 // The values rate per time unit (usually 1 second)
  65. Sum float64 // The sum of values
  66. SumSq float64 `json:"-"` // The sum of squared values
  67. Min float64 // Minimum value
  68. Max float64 // Maximum value
  69. LastUpdated time.Time `json:"-"` // When value was last updated
  70. }
  71. // Computes a Stddev of the values
  72. func (a *AggregateSample) Stddev() float64 {
  73. num := (float64(a.Count) * a.SumSq) - math.Pow(a.Sum, 2)
  74. div := float64(a.Count * (a.Count - 1))
  75. if div == 0 {
  76. return 0
  77. }
  78. return math.Sqrt(num / div)
  79. }
  80. // Computes a mean of the values
  81. func (a *AggregateSample) Mean() float64 {
  82. if a.Count == 0 {
  83. return 0
  84. }
  85. return a.Sum / float64(a.Count)
  86. }
  87. // Ingest is used to update a sample
  88. func (a *AggregateSample) Ingest(v float64, rateDenom float64) {
  89. a.Count++
  90. a.Sum += v
  91. a.SumSq += (v * v)
  92. if v < a.Min || a.Count == 1 {
  93. a.Min = v
  94. }
  95. if v > a.Max || a.Count == 1 {
  96. a.Max = v
  97. }
  98. a.Rate = float64(a.Sum) / rateDenom
  99. a.LastUpdated = time.Now()
  100. }
  101. func (a *AggregateSample) String() string {
  102. if a.Count == 0 {
  103. return "Count: 0"
  104. } else if a.Stddev() == 0 {
  105. return fmt.Sprintf("Count: %d Sum: %0.3f LastUpdated: %s", a.Count, a.Sum, a.LastUpdated)
  106. } else {
  107. return fmt.Sprintf("Count: %d Min: %0.3f Mean: %0.3f Max: %0.3f Stddev: %0.3f Sum: %0.3f LastUpdated: %s",
  108. a.Count, a.Min, a.Mean(), a.Max, a.Stddev(), a.Sum, a.LastUpdated)
  109. }
  110. }
  111. // NewInmemSinkFromURL creates an InmemSink from a URL. It is used
  112. // (and tested) from NewMetricSinkFromURL.
  113. func NewInmemSinkFromURL(u *url.URL) (MetricSink, error) {
  114. params := u.Query()
  115. interval, err := time.ParseDuration(params.Get("interval"))
  116. if err != nil {
  117. return nil, fmt.Errorf("Bad 'interval' param: %s", err)
  118. }
  119. retain, err := time.ParseDuration(params.Get("retain"))
  120. if err != nil {
  121. return nil, fmt.Errorf("Bad 'retain' param: %s", err)
  122. }
  123. return NewInmemSink(interval, retain), nil
  124. }
  125. // NewInmemSink is used to construct a new in-memory sink.
  126. // Uses an aggregation interval and maximum retention period.
  127. func NewInmemSink(interval, retain time.Duration) *InmemSink {
  128. rateTimeUnit := time.Second
  129. i := &InmemSink{
  130. interval: interval,
  131. retain: retain,
  132. maxIntervals: int(retain / interval),
  133. rateDenom: float64(interval.Nanoseconds()) / float64(rateTimeUnit.Nanoseconds()),
  134. }
  135. i.intervals = make([]*IntervalMetrics, 0, i.maxIntervals)
  136. return i
  137. }
  138. func (i *InmemSink) SetGauge(key []string, val float32) {
  139. i.SetGaugeWithLabels(key, val, nil)
  140. }
  141. func (i *InmemSink) SetGaugeWithLabels(key []string, val float32, labels []Label) {
  142. k, name := i.flattenKeyLabels(key, labels)
  143. intv := i.getInterval()
  144. intv.Lock()
  145. defer intv.Unlock()
  146. intv.Gauges[k] = GaugeValue{Name: name, Value: val, Labels: labels}
  147. }
  148. func (i *InmemSink) EmitKey(key []string, val float32) {
  149. k := i.flattenKey(key)
  150. intv := i.getInterval()
  151. intv.Lock()
  152. defer intv.Unlock()
  153. vals := intv.Points[k]
  154. intv.Points[k] = append(vals, val)
  155. }
  156. func (i *InmemSink) IncrCounter(key []string, val float32) {
  157. i.IncrCounterWithLabels(key, val, nil)
  158. }
  159. func (i *InmemSink) IncrCounterWithLabels(key []string, val float32, labels []Label) {
  160. k, name := i.flattenKeyLabels(key, labels)
  161. intv := i.getInterval()
  162. intv.Lock()
  163. defer intv.Unlock()
  164. agg, ok := intv.Counters[k]
  165. if !ok {
  166. agg = SampledValue{
  167. Name: name,
  168. AggregateSample: &AggregateSample{},
  169. Labels: labels,
  170. }
  171. intv.Counters[k] = agg
  172. }
  173. agg.Ingest(float64(val), i.rateDenom)
  174. }
  175. func (i *InmemSink) AddSample(key []string, val float32) {
  176. i.AddSampleWithLabels(key, val, nil)
  177. }
  178. func (i *InmemSink) AddSampleWithLabels(key []string, val float32, labels []Label) {
  179. k, name := i.flattenKeyLabels(key, labels)
  180. intv := i.getInterval()
  181. intv.Lock()
  182. defer intv.Unlock()
  183. agg, ok := intv.Samples[k]
  184. if !ok {
  185. agg = SampledValue{
  186. Name: name,
  187. AggregateSample: &AggregateSample{},
  188. Labels: labels,
  189. }
  190. intv.Samples[k] = agg
  191. }
  192. agg.Ingest(float64(val), i.rateDenom)
  193. }
  194. // Data is used to retrieve all the aggregated metrics
  195. // Intervals may be in use, and a read lock should be acquired
  196. func (i *InmemSink) Data() []*IntervalMetrics {
  197. // Get the current interval, forces creation
  198. i.getInterval()
  199. i.intervalLock.RLock()
  200. defer i.intervalLock.RUnlock()
  201. n := len(i.intervals)
  202. intervals := make([]*IntervalMetrics, n)
  203. copy(intervals[:n-1], i.intervals[:n-1])
  204. current := i.intervals[n-1]
  205. // make its own copy for current interval
  206. intervals[n-1] = &IntervalMetrics{}
  207. copyCurrent := intervals[n-1]
  208. current.RLock()
  209. *copyCurrent = *current
  210. // RWMutex is not safe to copy, so create a new instance on the copy
  211. copyCurrent.RWMutex = sync.RWMutex{}
  212. copyCurrent.Gauges = make(map[string]GaugeValue, len(current.Gauges))
  213. for k, v := range current.Gauges {
  214. copyCurrent.Gauges[k] = v
  215. }
  216. // saved values will be not change, just copy its link
  217. copyCurrent.Points = make(map[string][]float32, len(current.Points))
  218. for k, v := range current.Points {
  219. copyCurrent.Points[k] = v
  220. }
  221. copyCurrent.Counters = make(map[string]SampledValue, len(current.Counters))
  222. for k, v := range current.Counters {
  223. copyCurrent.Counters[k] = v.deepCopy()
  224. }
  225. copyCurrent.Samples = make(map[string]SampledValue, len(current.Samples))
  226. for k, v := range current.Samples {
  227. copyCurrent.Samples[k] = v.deepCopy()
  228. }
  229. current.RUnlock()
  230. return intervals
  231. }
  232. // getInterval returns the current interval. A new interval is created if no
  233. // previous interval exists, or if the current time is beyond the window for the
  234. // current interval.
  235. func (i *InmemSink) getInterval() *IntervalMetrics {
  236. intv := time.Now().Truncate(i.interval)
  237. // Attempt to return the existing interval first, because it only requires
  238. // a read lock.
  239. i.intervalLock.RLock()
  240. n := len(i.intervals)
  241. if n > 0 && i.intervals[n-1].Interval == intv {
  242. defer i.intervalLock.RUnlock()
  243. return i.intervals[n-1]
  244. }
  245. i.intervalLock.RUnlock()
  246. i.intervalLock.Lock()
  247. defer i.intervalLock.Unlock()
  248. // Re-check for an existing interval now that the lock is re-acquired.
  249. n = len(i.intervals)
  250. if n > 0 && i.intervals[n-1].Interval == intv {
  251. return i.intervals[n-1]
  252. }
  253. current := NewIntervalMetrics(intv)
  254. i.intervals = append(i.intervals, current)
  255. if n > 0 {
  256. close(i.intervals[n-1].done)
  257. }
  258. n++
  259. // Prune old intervals if the count exceeds the max.
  260. if n >= i.maxIntervals {
  261. copy(i.intervals[0:], i.intervals[n-i.maxIntervals:])
  262. i.intervals = i.intervals[:i.maxIntervals]
  263. }
  264. return current
  265. }
  266. // Flattens the key for formatting, removes spaces
  267. func (i *InmemSink) flattenKey(parts []string) string {
  268. buf := &bytes.Buffer{}
  269. joined := strings.Join(parts, ".")
  270. spaceReplacer.WriteString(buf, joined)
  271. return buf.String()
  272. }
  273. // Flattens the key for formatting along with its labels, removes spaces
  274. func (i *InmemSink) flattenKeyLabels(parts []string, labels []Label) (string, string) {
  275. key := i.flattenKey(parts)
  276. buf := bytes.NewBufferString(key)
  277. for _, label := range labels {
  278. spaceReplacer.WriteString(buf, fmt.Sprintf(";%s=%s", label.Name, label.Value))
  279. }
  280. return buf.String(), key
  281. }