labels.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package prometheus
  2. import (
  3. "errors"
  4. "fmt"
  5. "strings"
  6. "unicode/utf8"
  7. "github.com/prometheus/common/model"
  8. )
  9. // Labels represents a collection of label name -> value mappings. This type is
  10. // commonly used with the With(Labels) and GetMetricWith(Labels) methods of
  11. // metric vector Collectors, e.g.:
  12. // myVec.With(Labels{"code": "404", "method": "GET"}).Add(42)
  13. //
  14. // The other use-case is the specification of constant label pairs in Opts or to
  15. // create a Desc.
  16. type Labels map[string]string
  17. // reservedLabelPrefix is a prefix which is not legal in user-supplied
  18. // label names.
  19. const reservedLabelPrefix = "__"
  20. var errInconsistentCardinality = errors.New("inconsistent label cardinality")
  21. func validateValuesInLabels(labels Labels, expectedNumberOfValues int) error {
  22. if len(labels) != expectedNumberOfValues {
  23. return errInconsistentCardinality
  24. }
  25. for name, val := range labels {
  26. if !utf8.ValidString(val) {
  27. return fmt.Errorf("label %s: value %q is not valid UTF-8", name, val)
  28. }
  29. }
  30. return nil
  31. }
  32. func validateLabelValues(vals []string, expectedNumberOfValues int) error {
  33. if len(vals) != expectedNumberOfValues {
  34. return errInconsistentCardinality
  35. }
  36. for _, val := range vals {
  37. if !utf8.ValidString(val) {
  38. return fmt.Errorf("label value %q is not valid UTF-8", val)
  39. }
  40. }
  41. return nil
  42. }
  43. func checkLabelName(l string) bool {
  44. return model.LabelName(l).IsValid() && !strings.HasPrefix(l, reservedLabelPrefix)
  45. }