extract and refactor label validation functions

so that we can reuse them in other parts of the code, not only as part
of a metricVec.
This commit is contained in:
Marco Jantke 2017-08-19 22:56:18 +02:00
parent 957bba6f68
commit 459e88167e
2 changed files with 36 additions and 31 deletions

View File

@ -1 +1,35 @@
package prometheus package prometheus
import (
"errors"
"fmt"
"unicode/utf8"
)
func validateLabelValues(vals []string, expectedNumberOfValues int) error {
if len(vals) != expectedNumberOfValues {
return errInconsistentCardinality
}
for _, val := range vals {
if !utf8.ValidString(val) {
return errors.New(fmt.Sprintf("label %q is not valid utf8", val))
}
}
return nil
}
func validateLabels(labels Labels, expectedNumberOfValues int) error {
if len(labels) != expectedNumberOfValues {
return errInconsistentCardinality
}
for name, val := range labels {
if !utf8.ValidString(val) {
return errors.New(fmt.Sprintf("label %s: %q is not valid utf8", name, val))
}
}
return nil
}

View File

@ -14,10 +14,8 @@
package prometheus package prometheus
import ( import (
"errors"
"fmt" "fmt"
"sync" "sync"
"unicode/utf8"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
) )
@ -208,21 +206,8 @@ func (m *metricVec) Reset() {
} }
} }
func (m *metricVec) validateLabelValues(vals []string) error {
if len(vals) != len(m.desc.variableLabels) {
return errInconsistentCardinality
}
for _, val := range vals {
if !utf8.ValidString(val) {
return errors.New(fmt.Sprintf("label %q is not valid utf8", val))
}
}
return nil
}
func (m *metricVec) hashLabelValues(vals []string) (uint64, error) { func (m *metricVec) hashLabelValues(vals []string) (uint64, error) {
if err := m.validateLabelValues(vals); err != nil { if err := validateLabelValues(m.desc, vals); err != nil {
return 0, err return 0, err
} }
@ -234,22 +219,8 @@ func (m *metricVec) hashLabelValues(vals []string) (uint64, error) {
return h, nil return h, nil
} }
func (m *metricVec) validateLabels(labels Labels) error {
if len(labels) != len(m.desc.variableLabels) {
return errInconsistentCardinality
}
for name, val := range labels {
if !utf8.ValidString(val) {
return errors.New(fmt.Sprintf("label %s: %q is not valid utf8", name, val))
}
}
return nil
}
func (m *metricVec) hashLabels(labels Labels) (uint64, error) { func (m *metricVec) hashLabels(labels Labels) (uint64, error) {
if err := m.validateLabels(labels); err != nil { if err := validateLabels(m.desc, labels); err != nil {
return 0, err return 0, err
} }