metric.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright 2013 The Prometheus Authors
  2. // Licensed under the Apache License, Version 2.0 (the "License");
  3. // you may not use this file except in compliance with the License.
  4. // You may obtain a copy of the License at
  5. //
  6. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. package model
  14. import (
  15. "fmt"
  16. "sort"
  17. "strings"
  18. )
  19. var separator = []byte{0}
  20. // A Metric is similar to a LabelSet, but the key difference is that a Metric is
  21. // a singleton and refers to one and only one stream of samples.
  22. type Metric LabelSet
  23. // Equal compares the metrics.
  24. func (m Metric) Equal(o Metric) bool {
  25. return LabelSet(m).Equal(LabelSet(o))
  26. }
  27. // Before compares the metrics' underlying label sets.
  28. func (m Metric) Before(o Metric) bool {
  29. return LabelSet(m).Before(LabelSet(o))
  30. }
  31. // Clone returns a copy of the Metric.
  32. func (m Metric) Clone() Metric {
  33. clone := Metric{}
  34. for k, v := range m {
  35. clone[k] = v
  36. }
  37. return clone
  38. }
  39. func (m Metric) String() string {
  40. metricName, hasName := m[MetricNameLabel]
  41. numLabels := len(m) - 1
  42. if !hasName {
  43. numLabels = len(m)
  44. }
  45. labelStrings := make([]string, 0, numLabels)
  46. for label, value := range m {
  47. if label != MetricNameLabel {
  48. labelStrings = append(labelStrings, fmt.Sprintf("%s=%q", label, value))
  49. }
  50. }
  51. switch numLabels {
  52. case 0:
  53. if hasName {
  54. return string(metricName)
  55. }
  56. return "{}"
  57. default:
  58. sort.Strings(labelStrings)
  59. return fmt.Sprintf("%s{%s}", metricName, strings.Join(labelStrings, ", "))
  60. }
  61. }
  62. // Fingerprint returns a Metric's Fingerprint.
  63. func (m Metric) Fingerprint() Fingerprint {
  64. return LabelSet(m).Fingerprint()
  65. }
  66. // FastFingerprint returns a Metric's Fingerprint calculated by a faster hashing
  67. // algorithm, which is, however, more susceptible to hash collisions.
  68. func (m Metric) FastFingerprint() Fingerprint {
  69. return LabelSet(m).FastFingerprint()
  70. }