registry.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. package metrics
  2. import (
  3. "fmt"
  4. "reflect"
  5. "strings"
  6. "sync"
  7. )
  8. // DuplicateMetric is the error returned by Registry.Register when a metric
  9. // already exists. If you mean to Register that metric you must first
  10. // Unregister the existing metric.
  11. type DuplicateMetric string
  12. func (err DuplicateMetric) Error() string {
  13. return fmt.Sprintf("duplicate metric: %s", string(err))
  14. }
  15. // A Registry holds references to a set of metrics by name and can iterate
  16. // over them, calling callback functions provided by the user.
  17. //
  18. // This is an interface so as to encourage other structs to implement
  19. // the Registry API as appropriate.
  20. type Registry interface {
  21. // Call the given function for each registered metric.
  22. Each(func(string, interface{}))
  23. // Get the metric by the given name or nil if none is registered.
  24. Get(string) interface{}
  25. // Gets an existing metric or registers the given one.
  26. // The interface can be the metric to register if not found in registry,
  27. // or a function returning the metric for lazy instantiation.
  28. GetOrRegister(string, interface{}) interface{}
  29. // Register the given metric under the given name.
  30. Register(string, interface{}) error
  31. // Run all registered healthchecks.
  32. RunHealthchecks()
  33. // Unregister the metric with the given name.
  34. Unregister(string)
  35. // Unregister all metrics. (Mostly for testing.)
  36. UnregisterAll()
  37. }
  38. // The standard implementation of a Registry is a mutex-protected map
  39. // of names to metrics.
  40. type StandardRegistry struct {
  41. metrics map[string]interface{}
  42. mutex sync.Mutex
  43. }
  44. // Create a new registry.
  45. func NewRegistry() Registry {
  46. return &StandardRegistry{metrics: make(map[string]interface{})}
  47. }
  48. // Call the given function for each registered metric.
  49. func (r *StandardRegistry) Each(f func(string, interface{})) {
  50. for name, i := range r.registered() {
  51. f(name, i)
  52. }
  53. }
  54. // Get the metric by the given name or nil if none is registered.
  55. func (r *StandardRegistry) Get(name string) interface{} {
  56. r.mutex.Lock()
  57. defer r.mutex.Unlock()
  58. return r.metrics[name]
  59. }
  60. // Gets an existing metric or creates and registers a new one. Threadsafe
  61. // alternative to calling Get and Register on failure.
  62. // The interface can be the metric to register if not found in registry,
  63. // or a function returning the metric for lazy instantiation.
  64. func (r *StandardRegistry) GetOrRegister(name string, i interface{}) interface{} {
  65. r.mutex.Lock()
  66. defer r.mutex.Unlock()
  67. if metric, ok := r.metrics[name]; ok {
  68. return metric
  69. }
  70. if v := reflect.ValueOf(i); v.Kind() == reflect.Func {
  71. i = v.Call(nil)[0].Interface()
  72. }
  73. r.register(name, i)
  74. return i
  75. }
  76. // Register the given metric under the given name. Returns a DuplicateMetric
  77. // if a metric by the given name is already registered.
  78. func (r *StandardRegistry) Register(name string, i interface{}) error {
  79. r.mutex.Lock()
  80. defer r.mutex.Unlock()
  81. return r.register(name, i)
  82. }
  83. // Run all registered healthchecks.
  84. func (r *StandardRegistry) RunHealthchecks() {
  85. r.mutex.Lock()
  86. defer r.mutex.Unlock()
  87. for _, i := range r.metrics {
  88. if h, ok := i.(Healthcheck); ok {
  89. h.Check()
  90. }
  91. }
  92. }
  93. // Unregister the metric with the given name.
  94. func (r *StandardRegistry) Unregister(name string) {
  95. r.mutex.Lock()
  96. defer r.mutex.Unlock()
  97. r.stop(name)
  98. delete(r.metrics, name)
  99. }
  100. // Unregister all metrics. (Mostly for testing.)
  101. func (r *StandardRegistry) UnregisterAll() {
  102. r.mutex.Lock()
  103. defer r.mutex.Unlock()
  104. for name, _ := range r.metrics {
  105. r.stop(name)
  106. delete(r.metrics, name)
  107. }
  108. }
  109. func (r *StandardRegistry) register(name string, i interface{}) error {
  110. if _, ok := r.metrics[name]; ok {
  111. return DuplicateMetric(name)
  112. }
  113. switch i.(type) {
  114. case Counter, Gauge, GaugeFloat64, Healthcheck, Histogram, Meter, Timer:
  115. r.metrics[name] = i
  116. }
  117. return nil
  118. }
  119. func (r *StandardRegistry) registered() map[string]interface{} {
  120. r.mutex.Lock()
  121. defer r.mutex.Unlock()
  122. metrics := make(map[string]interface{}, len(r.metrics))
  123. for name, i := range r.metrics {
  124. metrics[name] = i
  125. }
  126. return metrics
  127. }
  128. func (r *StandardRegistry) stop(name string) {
  129. if i, ok := r.metrics[name]; ok {
  130. if s, ok := i.(Stoppable); ok {
  131. s.Stop()
  132. }
  133. }
  134. }
  135. // Stoppable defines the metrics which has to be stopped.
  136. type Stoppable interface {
  137. Stop()
  138. }
  139. type PrefixedRegistry struct {
  140. underlying Registry
  141. prefix string
  142. }
  143. func NewPrefixedRegistry(prefix string) Registry {
  144. return &PrefixedRegistry{
  145. underlying: NewRegistry(),
  146. prefix: prefix,
  147. }
  148. }
  149. func NewPrefixedChildRegistry(parent Registry, prefix string) Registry {
  150. return &PrefixedRegistry{
  151. underlying: parent,
  152. prefix: prefix,
  153. }
  154. }
  155. // Call the given function for each registered metric.
  156. func (r *PrefixedRegistry) Each(fn func(string, interface{})) {
  157. wrappedFn := func(prefix string) func(string, interface{}) {
  158. return func(name string, iface interface{}) {
  159. if strings.HasPrefix(name, prefix) {
  160. fn(name, iface)
  161. } else {
  162. return
  163. }
  164. }
  165. }
  166. baseRegistry, prefix := findPrefix(r, "")
  167. baseRegistry.Each(wrappedFn(prefix))
  168. }
  169. func findPrefix(registry Registry, prefix string) (Registry, string) {
  170. switch r := registry.(type) {
  171. case *PrefixedRegistry:
  172. return findPrefix(r.underlying, r.prefix+prefix)
  173. case *StandardRegistry:
  174. return r, prefix
  175. }
  176. return nil, ""
  177. }
  178. // Get the metric by the given name or nil if none is registered.
  179. func (r *PrefixedRegistry) Get(name string) interface{} {
  180. realName := r.prefix + name
  181. return r.underlying.Get(realName)
  182. }
  183. // Gets an existing metric or registers the given one.
  184. // The interface can be the metric to register if not found in registry,
  185. // or a function returning the metric for lazy instantiation.
  186. func (r *PrefixedRegistry) GetOrRegister(name string, metric interface{}) interface{} {
  187. realName := r.prefix + name
  188. return r.underlying.GetOrRegister(realName, metric)
  189. }
  190. // Register the given metric under the given name. The name will be prefixed.
  191. func (r *PrefixedRegistry) Register(name string, metric interface{}) error {
  192. realName := r.prefix + name
  193. return r.underlying.Register(realName, metric)
  194. }
  195. // Run all registered healthchecks.
  196. func (r *PrefixedRegistry) RunHealthchecks() {
  197. r.underlying.RunHealthchecks()
  198. }
  199. // Unregister the metric with the given name. The name will be prefixed.
  200. func (r *PrefixedRegistry) Unregister(name string) {
  201. realName := r.prefix + name
  202. r.underlying.Unregister(realName)
  203. }
  204. // Unregister all metrics. (Mostly for testing.)
  205. func (r *PrefixedRegistry) UnregisterAll() {
  206. r.underlying.UnregisterAll()
  207. }
  208. var DefaultRegistry Registry = NewRegistry()
  209. // Call the given function for each registered metric.
  210. func Each(f func(string, interface{})) {
  211. DefaultRegistry.Each(f)
  212. }
  213. // Get the metric by the given name or nil if none is registered.
  214. func Get(name string) interface{} {
  215. return DefaultRegistry.Get(name)
  216. }
  217. // Gets an existing metric or creates and registers a new one. Threadsafe
  218. // alternative to calling Get and Register on failure.
  219. func GetOrRegister(name string, i interface{}) interface{} {
  220. return DefaultRegistry.GetOrRegister(name, i)
  221. }
  222. // Register the given metric under the given name. Returns a DuplicateMetric
  223. // if a metric by the given name is already registered.
  224. func Register(name string, i interface{}) error {
  225. return DefaultRegistry.Register(name, i)
  226. }
  227. // Register the given metric under the given name. Panics if a metric by the
  228. // given name is already registered.
  229. func MustRegister(name string, i interface{}) {
  230. if err := Register(name, i); err != nil {
  231. panic(err)
  232. }
  233. }
  234. // Run all registered healthchecks.
  235. func RunHealthchecks() {
  236. DefaultRegistry.RunHealthchecks()
  237. }
  238. // Unregister the metric with the given name.
  239. func Unregister(name string) {
  240. DefaultRegistry.Unregister(name)
  241. }