labels.go 2.0 KB

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