metrics.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Package metrics provides metrics view of variables which is exposed through
  15. // expvar package.
  16. //
  17. // Naming conventions:
  18. // 1. volatile path components should be kept as deep into the hierarchy as possible
  19. // 2. each path component should have a clear and well-defined purpose
  20. // 3. components.separated.with.dot, and put package prefix at the head
  21. // 4. words_separated_with_underscore, and put clarifiers last, e.g., requests_total
  22. package metrics
  23. import (
  24. "bytes"
  25. "expvar"
  26. "fmt"
  27. "sort"
  28. "sync"
  29. )
  30. // Counter is a number that increases over time monotonically.
  31. type Counter struct{ i *expvar.Int }
  32. func (c *Counter) Add() { c.i.Add(1) }
  33. func (c *Counter) AddBy(delta int64) { c.i.Add(delta) }
  34. func (c *Counter) String() string { return c.i.String() }
  35. // Gauge returns instantaneous value that is expected to fluctuate over time.
  36. type Gauge struct{ i *expvar.Int }
  37. func (g *Gauge) Set(value int64) { g.i.Set(value) }
  38. func (g *Gauge) String() string { return g.i.String() }
  39. type nilVar struct{}
  40. func (v *nilVar) String() string { return "nil" }
  41. // Map aggregates Counters and Gauges.
  42. type Map struct{ *expvar.Map }
  43. func (m *Map) NewCounter(key string) *Counter {
  44. c := &Counter{i: new(expvar.Int)}
  45. m.Set(key, c)
  46. return c
  47. }
  48. func (m *Map) NewGauge(key string) *Gauge {
  49. g := &Gauge{i: new(expvar.Int)}
  50. m.Set(key, g)
  51. return g
  52. }
  53. // TODO: remove the var from the map to avoid memory boom
  54. func (m *Map) Delete(key string) { m.Set(key, &nilVar{}) }
  55. // String returns JSON format string that represents the group.
  56. // It does not print out nilVar.
  57. func (m *Map) String() string {
  58. var b bytes.Buffer
  59. fmt.Fprintf(&b, "{")
  60. first := true
  61. m.Do(func(kv expvar.KeyValue) {
  62. v := kv.Value.String()
  63. if v == "nil" {
  64. return
  65. }
  66. if !first {
  67. fmt.Fprintf(&b, ", ")
  68. }
  69. fmt.Fprintf(&b, "%q: %v", kv.Key, v)
  70. first = false
  71. })
  72. fmt.Fprintf(&b, "}")
  73. return b.String()
  74. }
  75. // All published variables.
  76. var (
  77. mutex sync.RWMutex
  78. vars = make(map[string]expvar.Var)
  79. varKeys []string // sorted
  80. )
  81. // Publish declares a named exported variable.
  82. // If the name is already registered then this will overwrite the old one.
  83. func Publish(name string, v expvar.Var) {
  84. mutex.Lock()
  85. defer mutex.Unlock()
  86. if _, existing := vars[name]; !existing {
  87. varKeys = append(varKeys, name)
  88. }
  89. sort.Strings(varKeys)
  90. vars[name] = v
  91. return
  92. }
  93. // Get retrieves a named exported variable.
  94. func Get(name string) expvar.Var {
  95. mutex.RLock()
  96. defer mutex.RUnlock()
  97. return vars[name]
  98. }
  99. // Convenience functions for creating new exported variables.
  100. func NewCounter(name string) *Counter {
  101. c := &Counter{i: new(expvar.Int)}
  102. Publish(name, c)
  103. return c
  104. }
  105. func NewGauge(name string) *Gauge {
  106. g := &Gauge{i: new(expvar.Int)}
  107. Publish(name, g)
  108. return g
  109. }
  110. func NewMap(name string) *Map {
  111. m := &Map{Map: new(expvar.Map).Init()}
  112. Publish(name, m)
  113. return m
  114. }
  115. // GetMap returns the map if it exists, or inits the given name map if it does
  116. // not exist.
  117. func GetMap(name string) *Map {
  118. v := Get(name)
  119. if v == nil {
  120. return NewMap(name)
  121. }
  122. return v.(*Map)
  123. }
  124. // Do calls f for each exported variable.
  125. // The global variable map is locked during the iteration,
  126. // but existing entries may be concurrently updated.
  127. func Do(f func(expvar.KeyValue)) {
  128. mutex.RLock()
  129. defer mutex.RUnlock()
  130. for _, k := range varKeys {
  131. f(expvar.KeyValue{k, vars[k]})
  132. }
  133. }
  134. // for test only
  135. func reset() {
  136. mutex.Lock()
  137. defer mutex.Unlock()
  138. vars = make(map[string]expvar.Var)
  139. varKeys = nil
  140. }