metrics.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. // Copyright (c) 2017 Uber Technologies, 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
  15. import (
  16. "fmt"
  17. "reflect"
  18. "strconv"
  19. "strings"
  20. )
  21. // MustInit initializes the passed in metrics and initializes its fields using the passed in factory.
  22. //
  23. // It uses reflection to initialize a struct containing metrics fields
  24. // by assigning new Counter/Gauge/Timer values with the metric name retrieved
  25. // from the `metric` tag and stats tags retrieved from the `tags` tag.
  26. //
  27. // Note: all fields of the struct must be exported, have a `metric` tag, and be
  28. // of type Counter or Gauge or Timer.
  29. //
  30. // Errors during Init lead to a panic.
  31. func MustInit(metrics interface{}, factory Factory, globalTags map[string]string) {
  32. if err := Init(metrics, factory, globalTags); err != nil {
  33. panic(err.Error())
  34. }
  35. }
  36. // Init does the same as MustInit, but returns an error instead of
  37. // panicking.
  38. func Init(m interface{}, factory Factory, globalTags map[string]string) error {
  39. // Allow user to opt out of reporting metrics by passing in nil.
  40. if factory == nil {
  41. factory = NullFactory
  42. }
  43. counterPtrType := reflect.TypeOf((*Counter)(nil)).Elem()
  44. gaugePtrType := reflect.TypeOf((*Gauge)(nil)).Elem()
  45. timerPtrType := reflect.TypeOf((*Timer)(nil)).Elem()
  46. histogramPtrType := reflect.TypeOf((*Histogram)(nil)).Elem()
  47. v := reflect.ValueOf(m).Elem()
  48. t := v.Type()
  49. for i := 0; i < t.NumField(); i++ {
  50. tags := make(map[string]string)
  51. for k, v := range globalTags {
  52. tags[k] = v
  53. }
  54. var buckets []float64
  55. field := t.Field(i)
  56. metric := field.Tag.Get("metric")
  57. if metric == "" {
  58. return fmt.Errorf("Field %s is missing a tag 'metric'", field.Name)
  59. }
  60. if tagString := field.Tag.Get("tags"); tagString != "" {
  61. tagPairs := strings.Split(tagString, ",")
  62. for _, tagPair := range tagPairs {
  63. tag := strings.Split(tagPair, "=")
  64. if len(tag) != 2 {
  65. return fmt.Errorf(
  66. "Field [%s]: Tag [%s] is not of the form key=value in 'tags' string [%s]",
  67. field.Name, tagPair, tagString)
  68. }
  69. tags[tag[0]] = tag[1]
  70. }
  71. }
  72. if bucketString := field.Tag.Get("buckets"); bucketString != "" {
  73. if field.Type.AssignableTo(timerPtrType) {
  74. // TODO: Parse timer duration buckets
  75. return fmt.Errorf(
  76. "Field [%s]: Buckets are not currently initialized for timer metrics",
  77. field.Name)
  78. } else if field.Type.AssignableTo(histogramPtrType) {
  79. bucketValues := strings.Split(bucketString, ",")
  80. for _, bucket := range bucketValues {
  81. b, err := strconv.ParseFloat(bucket, 64)
  82. if err != nil {
  83. return fmt.Errorf(
  84. "Field [%s]: Bucket [%s] could not be converted to float64 in 'buckets' string [%s]",
  85. field.Name, bucket, bucketString)
  86. }
  87. buckets = append(buckets, b)
  88. }
  89. } else {
  90. return fmt.Errorf(
  91. "Field [%s]: Buckets should only be defined for Timer and Histogram metric types",
  92. field.Name)
  93. }
  94. }
  95. help := field.Tag.Get("help")
  96. var obj interface{}
  97. if field.Type.AssignableTo(counterPtrType) {
  98. obj = factory.Counter(Options{
  99. Name: metric,
  100. Tags: tags,
  101. Help: help,
  102. })
  103. } else if field.Type.AssignableTo(gaugePtrType) {
  104. obj = factory.Gauge(Options{
  105. Name: metric,
  106. Tags: tags,
  107. Help: help,
  108. })
  109. } else if field.Type.AssignableTo(timerPtrType) {
  110. // TODO: Add buckets once parsed (see TODO above)
  111. obj = factory.Timer(TimerOptions{
  112. Name: metric,
  113. Tags: tags,
  114. Help: help,
  115. })
  116. } else if field.Type.AssignableTo(histogramPtrType) {
  117. obj = factory.Histogram(HistogramOptions{
  118. Name: metric,
  119. Tags: tags,
  120. Help: help,
  121. Buckets: buckets,
  122. })
  123. } else {
  124. return fmt.Errorf(
  125. "Field %s is not a pointer to timer, gauge, or counter",
  126. field.Name)
  127. }
  128. v.Field(i).Set(reflect.ValueOf(obj))
  129. }
  130. return nil
  131. }