inmem.go 8.8 KB

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