Merge pull request #365 from prometheus/beorn7/vec
Allow currying of metric vec's
This commit is contained in:
commit
180b8fdc22
|
@ -111,7 +111,7 @@ func NewCounterVec(opts CounterOpts, labelNames []string) *CounterVec {
|
||||||
// Counter with the same label values is created later.
|
// Counter with the same label values is created later.
|
||||||
//
|
//
|
||||||
// An error is returned if the number of label values is not the same as the
|
// An error is returned if the number of label values is not the same as the
|
||||||
// number of VariableLabels in Desc.
|
// number of VariableLabels in Desc (minus any curried labels).
|
||||||
//
|
//
|
||||||
// Note that for more than one label value, this method is prone to mistakes
|
// Note that for more than one label value, this method is prone to mistakes
|
||||||
// caused by an incorrect order of arguments. Consider GetMetricWith(Labels) as
|
// caused by an incorrect order of arguments. Consider GetMetricWith(Labels) as
|
||||||
|
@ -119,8 +119,8 @@ func NewCounterVec(opts CounterOpts, labelNames []string) *CounterVec {
|
||||||
// latter has a much more readable (albeit more verbose) syntax, but it comes
|
// latter has a much more readable (albeit more verbose) syntax, but it comes
|
||||||
// with a performance overhead (for creating and processing the Labels map).
|
// with a performance overhead (for creating and processing the Labels map).
|
||||||
// See also the GaugeVec example.
|
// See also the GaugeVec example.
|
||||||
func (m *CounterVec) GetMetricWithLabelValues(lvs ...string) (Counter, error) {
|
func (v *CounterVec) GetMetricWithLabelValues(lvs ...string) (Counter, error) {
|
||||||
metric, err := m.metricVec.getMetricWithLabelValues(lvs...)
|
metric, err := v.metricVec.getMetricWithLabelValues(lvs...)
|
||||||
if metric != nil {
|
if metric != nil {
|
||||||
return metric.(Counter), err
|
return metric.(Counter), err
|
||||||
}
|
}
|
||||||
|
@ -134,13 +134,13 @@ func (m *CounterVec) GetMetricWithLabelValues(lvs ...string) (Counter, error) {
|
||||||
// the same as for GetMetricWithLabelValues.
|
// the same as for GetMetricWithLabelValues.
|
||||||
//
|
//
|
||||||
// An error is returned if the number and names of the Labels are inconsistent
|
// An error is returned if the number and names of the Labels are inconsistent
|
||||||
// with those of the VariableLabels in Desc.
|
// with those of the VariableLabels in Desc (minus any curried labels).
|
||||||
//
|
//
|
||||||
// This method is used for the same purpose as
|
// This method is used for the same purpose as
|
||||||
// GetMetricWithLabelValues(...string). See there for pros and cons of the two
|
// GetMetricWithLabelValues(...string). See there for pros and cons of the two
|
||||||
// methods.
|
// methods.
|
||||||
func (m *CounterVec) GetMetricWith(labels Labels) (Counter, error) {
|
func (v *CounterVec) GetMetricWith(labels Labels) (Counter, error) {
|
||||||
metric, err := m.metricVec.getMetricWith(labels)
|
metric, err := v.metricVec.getMetricWith(labels)
|
||||||
if metric != nil {
|
if metric != nil {
|
||||||
return metric.(Counter), err
|
return metric.(Counter), err
|
||||||
}
|
}
|
||||||
|
@ -148,18 +148,57 @@ func (m *CounterVec) GetMetricWith(labels Labels) (Counter, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// WithLabelValues works as GetMetricWithLabelValues, but panics where
|
// WithLabelValues works as GetMetricWithLabelValues, but panics where
|
||||||
// GetMetricWithLabelValues would have returned an error. By not returning an
|
// GetMetricWithLabelValues would have returned an error. Not returning an
|
||||||
// error, WithLabelValues allows shortcuts like
|
// error allows shortcuts like
|
||||||
// myVec.WithLabelValues("404", "GET").Add(42)
|
// myVec.WithLabelValues("404", "GET").Add(42)
|
||||||
func (m *CounterVec) WithLabelValues(lvs ...string) Counter {
|
func (v *CounterVec) WithLabelValues(lvs ...string) Counter {
|
||||||
return m.metricVec.withLabelValues(lvs...).(Counter)
|
c, err := v.GetMetricWithLabelValues(lvs...)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return c
|
||||||
}
|
}
|
||||||
|
|
||||||
// With works as GetMetricWith, but panics where GetMetricWithLabels would have
|
// With works as GetMetricWith, but panics where GetMetricWithLabels would have
|
||||||
// returned an error. By not returning an error, With allows shortcuts like
|
// returned an error. Not returning an error allows shortcuts like
|
||||||
// myVec.With(Labels{"code": "404", "method": "GET"}).Add(42)
|
// myVec.With(prometheus.Labels{"code": "404", "method": "GET"}).Add(42)
|
||||||
func (m *CounterVec) With(labels Labels) Counter {
|
func (v *CounterVec) With(labels Labels) Counter {
|
||||||
return m.metricVec.with(labels).(Counter)
|
c, err := v.GetMetricWith(labels)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
// CurryWith returns a vector curried with the provided labels, i.e. the
|
||||||
|
// returned vector has those labels pre-set for all labeled operations performed
|
||||||
|
// on it. The cardinality of the curried vector is reduced accordingly. The
|
||||||
|
// order of the remaining labels stays the same (just with the curried labels
|
||||||
|
// taken out of the sequence – which is relevant for the
|
||||||
|
// (GetMetric)WithLabelValues methods). It is possible to curry a curried
|
||||||
|
// vector, but only with labels not yet used for currying before.
|
||||||
|
//
|
||||||
|
// The metrics contained in the CounterVec are shared between the curried and
|
||||||
|
// uncurried vectors. They are just accessed differently. Curried and uncurried
|
||||||
|
// vectors behave identically in terms of collection. Only one must be
|
||||||
|
// registered with a given registry (usually the uncurried version). The Reset
|
||||||
|
// method deletes all metrics, even if called on a curried vector.
|
||||||
|
func (v *CounterVec) CurryWith(labels Labels) (*CounterVec, error) {
|
||||||
|
vec, err := v.curryWith(labels)
|
||||||
|
if vec != nil {
|
||||||
|
return &CounterVec{vec}, err
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// MustCurryWith works as CurryWith but panics where CurryWith would have
|
||||||
|
// returned an error.
|
||||||
|
func (v *CounterVec) MustCurryWith(labels Labels) *CounterVec {
|
||||||
|
vec, err := v.CurryWith(labels)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return vec
|
||||||
}
|
}
|
||||||
|
|
||||||
// CounterFunc is a Counter whose value is determined at collect time by calling a
|
// CounterFunc is a Counter whose value is determined at collect time by calling a
|
||||||
|
|
|
@ -73,8 +73,7 @@ type Desc struct {
|
||||||
// and therefore not part of the Desc. (They are managed within the Metric.)
|
// and therefore not part of the Desc. (They are managed within the Metric.)
|
||||||
//
|
//
|
||||||
// For constLabels, the label values are constant. Therefore, they are fully
|
// For constLabels, the label values are constant. Therefore, they are fully
|
||||||
// specified in the Desc. See the Opts documentation for the implications of
|
// specified in the Desc. See the Collector example for a usage pattern.
|
||||||
// constant labels.
|
|
||||||
func NewDesc(fqName, help string, variableLabels []string, constLabels Labels) *Desc {
|
func NewDesc(fqName, help string, variableLabels []string, constLabels Labels) *Desc {
|
||||||
d := &Desc{
|
d := &Desc{
|
||||||
fqName: fqName,
|
fqName: fqName,
|
||||||
|
|
|
@ -98,15 +98,15 @@ func NewGaugeVec(opts GaugeOpts, labelNames []string) *GaugeVec {
|
||||||
// example.
|
// example.
|
||||||
//
|
//
|
||||||
// An error is returned if the number of label values is not the same as the
|
// An error is returned if the number of label values is not the same as the
|
||||||
// number of VariableLabels in Desc.
|
// number of VariableLabels in Desc (minus any curried labels).
|
||||||
//
|
//
|
||||||
// Note that for more than one label value, this method is prone to mistakes
|
// Note that for more than one label value, this method is prone to mistakes
|
||||||
// caused by an incorrect order of arguments. Consider GetMetricWith(Labels) as
|
// caused by an incorrect order of arguments. Consider GetMetricWith(Labels) as
|
||||||
// an alternative to avoid that type of mistake. For higher label numbers, the
|
// an alternative to avoid that type of mistake. For higher label numbers, the
|
||||||
// latter has a much more readable (albeit more verbose) syntax, but it comes
|
// latter has a much more readable (albeit more verbose) syntax, but it comes
|
||||||
// with a performance overhead (for creating and processing the Labels map).
|
// with a performance overhead (for creating and processing the Labels map).
|
||||||
func (m *GaugeVec) GetMetricWithLabelValues(lvs ...string) (Gauge, error) {
|
func (v *GaugeVec) GetMetricWithLabelValues(lvs ...string) (Gauge, error) {
|
||||||
metric, err := m.metricVec.getMetricWithLabelValues(lvs...)
|
metric, err := v.metricVec.getMetricWithLabelValues(lvs...)
|
||||||
if metric != nil {
|
if metric != nil {
|
||||||
return metric.(Gauge), err
|
return metric.(Gauge), err
|
||||||
}
|
}
|
||||||
|
@ -120,13 +120,13 @@ func (m *GaugeVec) GetMetricWithLabelValues(lvs ...string) (Gauge, error) {
|
||||||
// the same as for GetMetricWithLabelValues.
|
// the same as for GetMetricWithLabelValues.
|
||||||
//
|
//
|
||||||
// An error is returned if the number and names of the Labels are inconsistent
|
// An error is returned if the number and names of the Labels are inconsistent
|
||||||
// with those of the VariableLabels in Desc.
|
// with those of the VariableLabels in Desc (minus any curried labels).
|
||||||
//
|
//
|
||||||
// This method is used for the same purpose as
|
// This method is used for the same purpose as
|
||||||
// GetMetricWithLabelValues(...string). See there for pros and cons of the two
|
// GetMetricWithLabelValues(...string). See there for pros and cons of the two
|
||||||
// methods.
|
// methods.
|
||||||
func (m *GaugeVec) GetMetricWith(labels Labels) (Gauge, error) {
|
func (v *GaugeVec) GetMetricWith(labels Labels) (Gauge, error) {
|
||||||
metric, err := m.metricVec.getMetricWith(labels)
|
metric, err := v.metricVec.getMetricWith(labels)
|
||||||
if metric != nil {
|
if metric != nil {
|
||||||
return metric.(Gauge), err
|
return metric.(Gauge), err
|
||||||
}
|
}
|
||||||
|
@ -134,18 +134,57 @@ func (m *GaugeVec) GetMetricWith(labels Labels) (Gauge, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// WithLabelValues works as GetMetricWithLabelValues, but panics where
|
// WithLabelValues works as GetMetricWithLabelValues, but panics where
|
||||||
// GetMetricWithLabelValues would have returned an error. By not returning an
|
// GetMetricWithLabelValues would have returned an error. Not returning an
|
||||||
// error, WithLabelValues allows shortcuts like
|
// error allows shortcuts like
|
||||||
// myVec.WithLabelValues("404", "GET").Add(42)
|
// myVec.WithLabelValues("404", "GET").Add(42)
|
||||||
func (m *GaugeVec) WithLabelValues(lvs ...string) Gauge {
|
func (v *GaugeVec) WithLabelValues(lvs ...string) Gauge {
|
||||||
return m.metricVec.withLabelValues(lvs...).(Gauge)
|
g, err := v.GetMetricWithLabelValues(lvs...)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return g
|
||||||
}
|
}
|
||||||
|
|
||||||
// With works as GetMetricWith, but panics where GetMetricWithLabels would have
|
// With works as GetMetricWith, but panics where GetMetricWithLabels would have
|
||||||
// returned an error. By not returning an error, With allows shortcuts like
|
// returned an error. Not returning an error allows shortcuts like
|
||||||
// myVec.With(Labels{"code": "404", "method": "GET"}).Add(42)
|
// myVec.With(prometheus.Labels{"code": "404", "method": "GET"}).Add(42)
|
||||||
func (m *GaugeVec) With(labels Labels) Gauge {
|
func (v *GaugeVec) With(labels Labels) Gauge {
|
||||||
return m.metricVec.with(labels).(Gauge)
|
g, err := v.GetMetricWith(labels)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return g
|
||||||
|
}
|
||||||
|
|
||||||
|
// CurryWith returns a vector curried with the provided labels, i.e. the
|
||||||
|
// returned vector has those labels pre-set for all labeled operations performed
|
||||||
|
// on it. The cardinality of the curried vector is reduced accordingly. The
|
||||||
|
// order of the remaining labels stays the same (just with the curried labels
|
||||||
|
// taken out of the sequence – which is relevant for the
|
||||||
|
// (GetMetric)WithLabelValues methods). It is possible to curry a curried
|
||||||
|
// vector, but only with labels not yet used for currying before.
|
||||||
|
//
|
||||||
|
// The metrics contained in the GaugeVec are shared between the curried and
|
||||||
|
// uncurried vectors. They are just accessed differently. Curried and uncurried
|
||||||
|
// vectors behave identically in terms of collection. Only one must be
|
||||||
|
// registered with a given registry (usually the uncurried version). The Reset
|
||||||
|
// method deletes all metrics, even if called on a curried vector.
|
||||||
|
func (v *GaugeVec) CurryWith(labels Labels) (*GaugeVec, error) {
|
||||||
|
vec, err := v.curryWith(labels)
|
||||||
|
if vec != nil {
|
||||||
|
return &GaugeVec{vec}, err
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// MustCurryWith works as CurryWith but panics where CurryWith would have
|
||||||
|
// returned an error.
|
||||||
|
func (v *GaugeVec) MustCurryWith(labels Labels) *GaugeVec {
|
||||||
|
vec, err := v.CurryWith(labels)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return vec
|
||||||
}
|
}
|
||||||
|
|
||||||
// GaugeFunc is a Gauge whose value is determined at collect time by calling a
|
// GaugeFunc is a Gauge whose value is determined at collect time by calling a
|
||||||
|
|
|
@ -126,23 +126,16 @@ type HistogramOpts struct {
|
||||||
// string.
|
// string.
|
||||||
Help string
|
Help string
|
||||||
|
|
||||||
// ConstLabels are used to attach fixed labels to this
|
// ConstLabels are used to attach fixed labels to this metric. Metrics
|
||||||
// Histogram. Histograms with the same fully-qualified name must have the
|
// with the same fully-qualified name must have the same label names in
|
||||||
// same label names in their ConstLabels.
|
// their ConstLabels.
|
||||||
//
|
//
|
||||||
// Note that in most cases, labels have a value that varies during the
|
// ConstLabels are only used rarely. In particular, do not use them to
|
||||||
// lifetime of a process. Those labels are usually managed with a
|
// attach the same labels to all your metrics. Those use cases are
|
||||||
// HistogramVec. ConstLabels serve only special purposes. One is for the
|
// better covered by target labels set by the scraping Prometheus
|
||||||
// special case where the value of a label does not change during the
|
// server, or by one specific metric (e.g. a build_info or a
|
||||||
// lifetime of a process, e.g. if the revision of the running binary is
|
// machine_role metric). See also
|
||||||
// put into a label. Another, more advanced purpose is if more than one
|
// https://prometheus.io/docs/instrumenting/writing_exporters/#target-labels,-not-static-scraped-labels
|
||||||
// Collector needs to collect Histograms with the same fully-qualified
|
|
||||||
// name. In that case, those Summaries must differ in the values of
|
|
||||||
// their ConstLabels. See the Collector examples.
|
|
||||||
//
|
|
||||||
// If the value of a label never changes (not even between binaries),
|
|
||||||
// that label most likely should not be a label at all (but part of the
|
|
||||||
// metric name).
|
|
||||||
ConstLabels Labels
|
ConstLabels Labels
|
||||||
|
|
||||||
// Buckets defines the buckets into which observations are counted. Each
|
// Buckets defines the buckets into which observations are counted. Each
|
||||||
|
@ -322,7 +315,7 @@ func NewHistogramVec(opts HistogramOpts, labelNames []string) *HistogramVec {
|
||||||
// example.
|
// example.
|
||||||
//
|
//
|
||||||
// An error is returned if the number of label values is not the same as the
|
// An error is returned if the number of label values is not the same as the
|
||||||
// number of VariableLabels in Desc.
|
// number of VariableLabels in Desc (minus any curried labels).
|
||||||
//
|
//
|
||||||
// Note that for more than one label value, this method is prone to mistakes
|
// Note that for more than one label value, this method is prone to mistakes
|
||||||
// caused by an incorrect order of arguments. Consider GetMetricWith(Labels) as
|
// caused by an incorrect order of arguments. Consider GetMetricWith(Labels) as
|
||||||
|
@ -330,8 +323,8 @@ func NewHistogramVec(opts HistogramOpts, labelNames []string) *HistogramVec {
|
||||||
// latter has a much more readable (albeit more verbose) syntax, but it comes
|
// latter has a much more readable (albeit more verbose) syntax, but it comes
|
||||||
// with a performance overhead (for creating and processing the Labels map).
|
// with a performance overhead (for creating and processing the Labels map).
|
||||||
// See also the GaugeVec example.
|
// See also the GaugeVec example.
|
||||||
func (m *HistogramVec) GetMetricWithLabelValues(lvs ...string) (Observer, error) {
|
func (v *HistogramVec) GetMetricWithLabelValues(lvs ...string) (Observer, error) {
|
||||||
metric, err := m.metricVec.getMetricWithLabelValues(lvs...)
|
metric, err := v.metricVec.getMetricWithLabelValues(lvs...)
|
||||||
if metric != nil {
|
if metric != nil {
|
||||||
return metric.(Observer), err
|
return metric.(Observer), err
|
||||||
}
|
}
|
||||||
|
@ -345,13 +338,13 @@ func (m *HistogramVec) GetMetricWithLabelValues(lvs ...string) (Observer, error)
|
||||||
// are the same as for GetMetricWithLabelValues.
|
// are the same as for GetMetricWithLabelValues.
|
||||||
//
|
//
|
||||||
// An error is returned if the number and names of the Labels are inconsistent
|
// An error is returned if the number and names of the Labels are inconsistent
|
||||||
// with those of the VariableLabels in Desc.
|
// with those of the VariableLabels in Desc (minus any curried labels).
|
||||||
//
|
//
|
||||||
// This method is used for the same purpose as
|
// This method is used for the same purpose as
|
||||||
// GetMetricWithLabelValues(...string). See there for pros and cons of the two
|
// GetMetricWithLabelValues(...string). See there for pros and cons of the two
|
||||||
// methods.
|
// methods.
|
||||||
func (m *HistogramVec) GetMetricWith(labels Labels) (Observer, error) {
|
func (v *HistogramVec) GetMetricWith(labels Labels) (Observer, error) {
|
||||||
metric, err := m.metricVec.getMetricWith(labels)
|
metric, err := v.metricVec.getMetricWith(labels)
|
||||||
if metric != nil {
|
if metric != nil {
|
||||||
return metric.(Observer), err
|
return metric.(Observer), err
|
||||||
}
|
}
|
||||||
|
@ -359,18 +352,57 @@ func (m *HistogramVec) GetMetricWith(labels Labels) (Observer, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// WithLabelValues works as GetMetricWithLabelValues, but panics where
|
// WithLabelValues works as GetMetricWithLabelValues, but panics where
|
||||||
// GetMetricWithLabelValues would have returned an error. By not returning an
|
// GetMetricWithLabelValues would have returned an error. Not returning an
|
||||||
// error, WithLabelValues allows shortcuts like
|
// error allows shortcuts like
|
||||||
// myVec.WithLabelValues("404", "GET").Observe(42.21)
|
// myVec.WithLabelValues("404", "GET").Observe(42.21)
|
||||||
func (m *HistogramVec) WithLabelValues(lvs ...string) Observer {
|
func (v *HistogramVec) WithLabelValues(lvs ...string) Observer {
|
||||||
return m.metricVec.withLabelValues(lvs...).(Observer)
|
h, err := v.GetMetricWithLabelValues(lvs...)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return h
|
||||||
}
|
}
|
||||||
|
|
||||||
// With works as GetMetricWith, but panics where GetMetricWithLabels would have
|
// With works as GetMetricWith but panics where GetMetricWithLabels would have
|
||||||
// returned an error. By not returning an error, With allows shortcuts like
|
// returned an error. Not returning an error allows shortcuts like
|
||||||
// myVec.With(Labels{"code": "404", "method": "GET"}).Observe(42.21)
|
// myVec.With(prometheus.Labels{"code": "404", "method": "GET"}).Observe(42.21)
|
||||||
func (m *HistogramVec) With(labels Labels) Observer {
|
func (v *HistogramVec) With(labels Labels) Observer {
|
||||||
return m.metricVec.with(labels).(Observer)
|
h, err := v.GetMetricWith(labels)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return h
|
||||||
|
}
|
||||||
|
|
||||||
|
// CurryWith returns a vector curried with the provided labels, i.e. the
|
||||||
|
// returned vector has those labels pre-set for all labeled operations performed
|
||||||
|
// on it. The cardinality of the curried vector is reduced accordingly. The
|
||||||
|
// order of the remaining labels stays the same (just with the curried labels
|
||||||
|
// taken out of the sequence – which is relevant for the
|
||||||
|
// (GetMetric)WithLabelValues methods). It is possible to curry a curried
|
||||||
|
// vector, but only with labels not yet used for currying before.
|
||||||
|
//
|
||||||
|
// The metrics contained in the HistogramVec are shared between the curried and
|
||||||
|
// uncurried vectors. They are just accessed differently. Curried and uncurried
|
||||||
|
// vectors behave identically in terms of collection. Only one must be
|
||||||
|
// registered with a given registry (usually the uncurried version). The Reset
|
||||||
|
// method deletes all metrics, even if called on a curried vector.
|
||||||
|
func (v *HistogramVec) CurryWith(labels Labels) (ObserverVec, error) {
|
||||||
|
vec, err := v.curryWith(labels)
|
||||||
|
if vec != nil {
|
||||||
|
return &HistogramVec{vec}, err
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// MustCurryWith works as CurryWith but panics where CurryWith would have
|
||||||
|
// returned an error.
|
||||||
|
func (v *HistogramVec) MustCurryWith(labels Labels) ObserverVec {
|
||||||
|
vec, err := v.CurryWith(labels)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return vec
|
||||||
}
|
}
|
||||||
|
|
||||||
type constHistogram struct {
|
type constHistogram struct {
|
||||||
|
|
|
@ -128,7 +128,7 @@ func TestInstrumentHandler(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
out.Reset()
|
out.Reset()
|
||||||
if want, got := 1, len(reqCnt.children); want != got {
|
if want, got := 1, len(reqCnt.metricMap.metrics); want != got {
|
||||||
t.Errorf("want %d children in reqCnt, got %d", want, got)
|
t.Errorf("want %d children in reqCnt, got %d", want, got)
|
||||||
}
|
}
|
||||||
cnt, err := reqCnt.GetMetricWithLabelValues("get", "418")
|
cnt, err := reqCnt.GetMetricWithLabelValues("get", "418")
|
||||||
|
|
|
@ -79,20 +79,12 @@ type Opts struct {
|
||||||
// with the same fully-qualified name must have the same label names in
|
// with the same fully-qualified name must have the same label names in
|
||||||
// their ConstLabels.
|
// their ConstLabels.
|
||||||
//
|
//
|
||||||
// Note that in most cases, labels have a value that varies during the
|
// ConstLabels are only used rarely. In particular, do not use them to
|
||||||
// lifetime of a process. Those labels are usually managed with a metric
|
// attach the same labels to all your metrics. Those use cases are
|
||||||
// vector collector (like CounterVec, GaugeVec, UntypedVec). ConstLabels
|
// better covered by target labels set by the scraping Prometheus
|
||||||
// serve only special purposes. One is for the special case where the
|
// server, or by one specific metric (e.g. a build_info or a
|
||||||
// value of a label does not change during the lifetime of a process,
|
// machine_role metric). See also
|
||||||
// e.g. if the revision of the running binary is put into a
|
// https://prometheus.io/docs/instrumenting/writing_exporters/#target-labels,-not-static-scraped-labels
|
||||||
// label. Another, more advanced purpose is if more than one Collector
|
|
||||||
// needs to collect Metrics with the same fully-qualified name. In that
|
|
||||||
// case, those Metrics must differ in the values of their
|
|
||||||
// ConstLabels. See the Collector examples.
|
|
||||||
//
|
|
||||||
// If the value of a label never changes (not even between binaries),
|
|
||||||
// that label most likely should not be a label at all (but part of the
|
|
||||||
// metric name).
|
|
||||||
ConstLabels Labels
|
ConstLabels Labels
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -45,6 +45,8 @@ type ObserverVec interface {
|
||||||
GetMetricWithLabelValues(lvs ...string) (Observer, error)
|
GetMetricWithLabelValues(lvs ...string) (Observer, error)
|
||||||
With(Labels) Observer
|
With(Labels) Observer
|
||||||
WithLabelValues(...string) Observer
|
WithLabelValues(...string) Observer
|
||||||
|
CurryWith(Labels) (ObserverVec, error)
|
||||||
|
MustCurryWith(Labels) ObserverVec
|
||||||
|
|
||||||
Collector
|
Collector
|
||||||
}
|
}
|
||||||
|
|
|
@ -45,12 +45,11 @@ func InstrumentRoundTripperInFlight(gauge prometheus.Gauge, next http.RoundTripp
|
||||||
|
|
||||||
// InstrumentRoundTripperCounter is a middleware that wraps the provided
|
// InstrumentRoundTripperCounter is a middleware that wraps the provided
|
||||||
// http.RoundTripper to observe the request result with the provided CounterVec.
|
// http.RoundTripper to observe the request result with the provided CounterVec.
|
||||||
// The CounterVec must have zero, one, or two labels. The only allowed label
|
// The CounterVec must have zero, one, or two non-const non-curried labels. For
|
||||||
// names are "code" and "method". The function panics if any other instance
|
// those, the only allowed label names are "code" and "method". The function
|
||||||
// labels are provided. Partitioning of the CounterVec happens by HTTP status
|
// panics otherwise. Partitioning of the CounterVec happens by HTTP status code
|
||||||
// code and/or HTTP method if the respective instance label names are present
|
// and/or HTTP method if the respective instance label names are present in the
|
||||||
// in the CounterVec. For unpartitioned counting, use a CounterVec with
|
// CounterVec. For unpartitioned counting, use a CounterVec with zero labels.
|
||||||
// zero labels.
|
|
||||||
//
|
//
|
||||||
// If the wrapped RoundTripper panics or returns a non-nil error, the Counter
|
// If the wrapped RoundTripper panics or returns a non-nil error, the Counter
|
||||||
// is not incremented.
|
// is not incremented.
|
||||||
|
|
|
@ -14,6 +14,7 @@
|
||||||
package promhttp
|
package promhttp
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
@ -42,10 +43,10 @@ func InstrumentHandlerInFlight(g prometheus.Gauge, next http.Handler) http.Handl
|
||||||
|
|
||||||
// InstrumentHandlerDuration is a middleware that wraps the provided
|
// InstrumentHandlerDuration is a middleware that wraps the provided
|
||||||
// http.Handler to observe the request duration with the provided ObserverVec.
|
// http.Handler to observe the request duration with the provided ObserverVec.
|
||||||
// The ObserverVec must have zero, one, or two labels. The only allowed label
|
// The ObserverVec must have zero, one, or two non-const non-curried labels. For
|
||||||
// names are "code" and "method". The function panics if any other instance
|
// those, the only allowed label names are "code" and "method". The function
|
||||||
// labels are provided. The Observe method of the Observer in the ObserverVec
|
// panics otherwise. The Observe method of the Observer in the ObserverVec is
|
||||||
// is called with the request duration in seconds. Partitioning happens by HTTP
|
// called with the request duration in seconds. Partitioning happens by HTTP
|
||||||
// status code and/or HTTP method if the respective instance label names are
|
// status code and/or HTTP method if the respective instance label names are
|
||||||
// present in the ObserverVec. For unpartitioned observations, use an
|
// present in the ObserverVec. For unpartitioned observations, use an
|
||||||
// ObserverVec with zero labels. Note that partitioning of Histograms is
|
// ObserverVec with zero labels. Note that partitioning of Histograms is
|
||||||
|
@ -77,14 +78,13 @@ func InstrumentHandlerDuration(obs prometheus.ObserverVec, next http.Handler) ht
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// InstrumentHandlerCounter is a middleware that wraps the provided
|
// InstrumentHandlerCounter is a middleware that wraps the provided http.Handler
|
||||||
// http.Handler to observe the request result with the provided CounterVec.
|
// to observe the request result with the provided CounterVec. The CounterVec
|
||||||
// The CounterVec must have zero, one, or two labels. The only allowed label
|
// must have zero, one, or two non-const non-curried labels. For those, the only
|
||||||
// names are "code" and "method". The function panics if any other instance
|
// allowed label names are "code" and "method". The function panics
|
||||||
// labels are provided. Partitioning of the CounterVec happens by HTTP status
|
// otherwise. Partitioning of the CounterVec happens by HTTP status code and/or
|
||||||
// code and/or HTTP method if the respective instance label names are present
|
// HTTP method if the respective instance label names are present in the
|
||||||
// in the CounterVec. For unpartitioned counting, use a CounterVec with
|
// CounterVec. For unpartitioned counting, use a CounterVec with zero labels.
|
||||||
// zero labels.
|
|
||||||
//
|
//
|
||||||
// If the wrapped Handler does not set a status code, a status code of 200 is assumed.
|
// If the wrapped Handler does not set a status code, a status code of 200 is assumed.
|
||||||
//
|
//
|
||||||
|
@ -111,14 +111,13 @@ func InstrumentHandlerCounter(counter *prometheus.CounterVec, next http.Handler)
|
||||||
// InstrumentHandlerTimeToWriteHeader is a middleware that wraps the provided
|
// InstrumentHandlerTimeToWriteHeader is a middleware that wraps the provided
|
||||||
// http.Handler to observe with the provided ObserverVec the request duration
|
// http.Handler to observe with the provided ObserverVec the request duration
|
||||||
// until the response headers are written. The ObserverVec must have zero, one,
|
// until the response headers are written. The ObserverVec must have zero, one,
|
||||||
// or two labels. The only allowed label names are "code" and "method". The
|
// or two non-const non-curried labels. For those, the only allowed label names
|
||||||
// function panics if any other instance labels are provided. The Observe
|
// are "code" and "method". The function panics otherwise. The Observe method of
|
||||||
// method of the Observer in the ObserverVec is called with the request
|
// the Observer in the ObserverVec is called with the request duration in
|
||||||
// duration in seconds. Partitioning happens by HTTP status code and/or HTTP
|
// seconds. Partitioning happens by HTTP status code and/or HTTP method if the
|
||||||
// method if the respective instance label names are present in the
|
// respective instance label names are present in the ObserverVec. For
|
||||||
// ObserverVec. For unpartitioned observations, use an ObserverVec with zero
|
// unpartitioned observations, use an ObserverVec with zero labels. Note that
|
||||||
// labels. Note that partitioning of Histograms is expensive and should be used
|
// partitioning of Histograms is expensive and should be used judiciously.
|
||||||
// judiciously.
|
|
||||||
//
|
//
|
||||||
// If the wrapped Handler panics before calling WriteHeader, no value is
|
// If the wrapped Handler panics before calling WriteHeader, no value is
|
||||||
// reported.
|
// reported.
|
||||||
|
@ -140,15 +139,15 @@ func InstrumentHandlerTimeToWriteHeader(obs prometheus.ObserverVec, next http.Ha
|
||||||
}
|
}
|
||||||
|
|
||||||
// InstrumentHandlerRequestSize is a middleware that wraps the provided
|
// InstrumentHandlerRequestSize is a middleware that wraps the provided
|
||||||
// http.Handler to observe the request size with the provided ObserverVec.
|
// http.Handler to observe the request size with the provided ObserverVec. The
|
||||||
// The ObserverVec must have zero, one, or two labels. The only allowed label
|
// ObserverVec must have zero, one, or two non-const non-curried labels. For
|
||||||
// names are "code" and "method". The function panics if any other instance
|
// those, the only allowed label names are "code" and "method". The function
|
||||||
// labels are provided. The Observe method of the Observer in the ObserverVec
|
// panics otherwise. The Observe method of the Observer in the ObserverVec is
|
||||||
// is called with the request size in bytes. Partitioning happens by HTTP
|
// called with the request size in bytes. Partitioning happens by HTTP status
|
||||||
// status code and/or HTTP method if the respective instance label names are
|
// code and/or HTTP method if the respective instance label names are present in
|
||||||
// present in the ObserverVec. For unpartitioned observations, use an
|
// the ObserverVec. For unpartitioned observations, use an ObserverVec with zero
|
||||||
// ObserverVec with zero labels. Note that partitioning of Histograms is
|
// labels. Note that partitioning of Histograms is expensive and should be used
|
||||||
// expensive and should be used judiciously.
|
// judiciously.
|
||||||
//
|
//
|
||||||
// If the wrapped Handler does not set a status code, a status code of 200 is assumed.
|
// If the wrapped Handler does not set a status code, a status code of 200 is assumed.
|
||||||
//
|
//
|
||||||
|
@ -175,15 +174,15 @@ func InstrumentHandlerRequestSize(obs prometheus.ObserverVec, next http.Handler)
|
||||||
}
|
}
|
||||||
|
|
||||||
// InstrumentHandlerResponseSize is a middleware that wraps the provided
|
// InstrumentHandlerResponseSize is a middleware that wraps the provided
|
||||||
// http.Handler to observe the response size with the provided ObserverVec.
|
// http.Handler to observe the response size with the provided ObserverVec. The
|
||||||
// The ObserverVec must have zero, one, or two labels. The only allowed label
|
// ObserverVec must have zero, one, or two non-const non-curried labels. For
|
||||||
// names are "code" and "method". The function panics if any other instance
|
// those, the only allowed label names are "code" and "method". The function
|
||||||
// labels are provided. The Observe method of the Observer in the ObserverVec
|
// panics otherwise. The Observe method of the Observer in the ObserverVec is
|
||||||
// is called with the response size in bytes. Partitioning happens by HTTP
|
// called with the response size in bytes. Partitioning happens by HTTP status
|
||||||
// status code and/or HTTP method if the respective instance label names are
|
// code and/or HTTP method if the respective instance label names are present in
|
||||||
// present in the ObserverVec. For unpartitioned observations, use an
|
// the ObserverVec. For unpartitioned observations, use an ObserverVec with zero
|
||||||
// ObserverVec with zero labels. Note that partitioning of Histograms is
|
// labels. Note that partitioning of Histograms is expensive and should be used
|
||||||
// expensive and should be used judiciously.
|
// judiciously.
|
||||||
//
|
//
|
||||||
// If the wrapped Handler does not set a status code, a status code of 200 is assumed.
|
// If the wrapped Handler does not set a status code, a status code of 200 is assumed.
|
||||||
//
|
//
|
||||||
|
@ -204,9 +203,12 @@ func checkLabels(c prometheus.Collector) (code bool, method bool) {
|
||||||
// once Descriptors can have their dimensionality queried.
|
// once Descriptors can have their dimensionality queried.
|
||||||
var (
|
var (
|
||||||
desc *prometheus.Desc
|
desc *prometheus.Desc
|
||||||
|
m prometheus.Metric
|
||||||
pm dto.Metric
|
pm dto.Metric
|
||||||
|
lvs []string
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Get the Desc from the Collector.
|
||||||
descc := make(chan *prometheus.Desc, 1)
|
descc := make(chan *prometheus.Desc, 1)
|
||||||
c.Describe(descc)
|
c.Describe(descc)
|
||||||
|
|
||||||
|
@ -223,49 +225,54 @@ func checkLabels(c prometheus.Collector) (code bool, method bool) {
|
||||||
|
|
||||||
close(descc)
|
close(descc)
|
||||||
|
|
||||||
if _, err := prometheus.NewConstMetric(desc, prometheus.UntypedValue, 0); err == nil {
|
// Create a ConstMetric with the Desc. Since we don't know how many
|
||||||
return
|
// variable labels there are, try for as long as it needs.
|
||||||
|
for err := errors.New("dummy"); err != nil; lvs = append(lvs, magicString) {
|
||||||
|
m, err = prometheus.NewConstMetric(desc, prometheus.UntypedValue, 0, lvs...)
|
||||||
}
|
}
|
||||||
if m, err := prometheus.NewConstMetric(desc, prometheus.UntypedValue, 0, magicString); err == nil {
|
|
||||||
if err := m.Write(&pm); err != nil {
|
// Write out the metric into a proto message and look at the labels.
|
||||||
panic("error checking metric for labels")
|
// If the value is not the magicString, it is a constLabel, which doesn't interest us.
|
||||||
}
|
// If the label is curried, it doesn't interest us.
|
||||||
for _, label := range pm.Label {
|
// In all other cases, only "code" or "method" is allowed.
|
||||||
name, value := label.GetName(), label.GetValue()
|
if err := m.Write(&pm); err != nil {
|
||||||
if value != magicString {
|
panic("error checking metric for labels")
|
||||||
continue
|
|
||||||
}
|
|
||||||
switch name {
|
|
||||||
case "code":
|
|
||||||
code = true
|
|
||||||
case "method":
|
|
||||||
method = true
|
|
||||||
default:
|
|
||||||
panic("metric partitioned with non-supported labels")
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
panic("previously set label not found – this must never happen")
|
|
||||||
}
|
}
|
||||||
if m, err := prometheus.NewConstMetric(desc, prometheus.UntypedValue, 0, magicString, magicString); err == nil {
|
for _, label := range pm.Label {
|
||||||
if err := m.Write(&pm); err != nil {
|
name, value := label.GetName(), label.GetValue()
|
||||||
panic("error checking metric for labels")
|
if value != magicString || isLabelCurried(c, name) {
|
||||||
|
continue
|
||||||
}
|
}
|
||||||
for _, label := range pm.Label {
|
switch name {
|
||||||
name, value := label.GetName(), label.GetValue()
|
case "code":
|
||||||
if value != magicString {
|
code = true
|
||||||
continue
|
case "method":
|
||||||
}
|
method = true
|
||||||
if name == "code" || name == "method" {
|
default:
|
||||||
continue
|
|
||||||
}
|
|
||||||
panic("metric partitioned with non-supported labels")
|
panic("metric partitioned with non-supported labels")
|
||||||
}
|
}
|
||||||
code = true
|
|
||||||
method = true
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
panic("metric partitioned with non-supported labels")
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func isLabelCurried(c prometheus.Collector, label string) bool {
|
||||||
|
// This is even hackier than the label test above.
|
||||||
|
// We essentially try to curry again and see if it works.
|
||||||
|
// But for that, we need to type-convert to the two
|
||||||
|
// types we use here, ObserverVec or *CounterVec.
|
||||||
|
switch v := c.(type) {
|
||||||
|
case *prometheus.CounterVec:
|
||||||
|
if _, err := v.CurryWith(prometheus.Labels{label: "dummy"}); err == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
case prometheus.ObserverVec:
|
||||||
|
if _, err := v.CurryWith(prometheus.Labels{label: "dummy"}); err == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
panic("unsupported metric vec type")
|
||||||
|
}
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// emptyLabels is a one-time allocation for non-partitioned metrics to avoid
|
// emptyLabels is a one-time allocation for non-partitioned metrics to avoid
|
||||||
|
|
|
@ -23,6 +23,162 @@ import (
|
||||||
"github.com/prometheus/client_golang/prometheus"
|
"github.com/prometheus/client_golang/prometheus"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestLabelCheck(t *testing.T) {
|
||||||
|
scenarios := map[string]struct {
|
||||||
|
varLabels []string
|
||||||
|
constLabels []string
|
||||||
|
curriedLabels []string
|
||||||
|
ok bool
|
||||||
|
}{
|
||||||
|
"empty": {
|
||||||
|
varLabels: []string{},
|
||||||
|
constLabels: []string{},
|
||||||
|
curriedLabels: []string{},
|
||||||
|
ok: true,
|
||||||
|
},
|
||||||
|
"code as single var label": {
|
||||||
|
varLabels: []string{"code"},
|
||||||
|
constLabels: []string{},
|
||||||
|
curriedLabels: []string{},
|
||||||
|
ok: true,
|
||||||
|
},
|
||||||
|
"method as single var label": {
|
||||||
|
varLabels: []string{"method"},
|
||||||
|
constLabels: []string{},
|
||||||
|
curriedLabels: []string{},
|
||||||
|
ok: true,
|
||||||
|
},
|
||||||
|
"cade and method as var labels": {
|
||||||
|
varLabels: []string{"method", "code"},
|
||||||
|
constLabels: []string{},
|
||||||
|
curriedLabels: []string{},
|
||||||
|
ok: true,
|
||||||
|
},
|
||||||
|
"valid case with all labels used": {
|
||||||
|
varLabels: []string{"code", "method"},
|
||||||
|
constLabels: []string{"foo", "bar"},
|
||||||
|
curriedLabels: []string{"dings", "bums"},
|
||||||
|
ok: true,
|
||||||
|
},
|
||||||
|
"unsupported var label": {
|
||||||
|
varLabels: []string{"foo"},
|
||||||
|
constLabels: []string{},
|
||||||
|
curriedLabels: []string{},
|
||||||
|
ok: false,
|
||||||
|
},
|
||||||
|
"mixed var labels": {
|
||||||
|
varLabels: []string{"method", "foo", "code"},
|
||||||
|
constLabels: []string{},
|
||||||
|
curriedLabels: []string{},
|
||||||
|
ok: false,
|
||||||
|
},
|
||||||
|
"unsupported var label but curried": {
|
||||||
|
varLabels: []string{},
|
||||||
|
constLabels: []string{},
|
||||||
|
curriedLabels: []string{"foo"},
|
||||||
|
ok: true,
|
||||||
|
},
|
||||||
|
"mixed var labels but unsupported curried": {
|
||||||
|
varLabels: []string{"code", "method"},
|
||||||
|
constLabels: []string{},
|
||||||
|
curriedLabels: []string{"foo"},
|
||||||
|
ok: true,
|
||||||
|
},
|
||||||
|
"supported label as const and curry": {
|
||||||
|
varLabels: []string{},
|
||||||
|
constLabels: []string{"code"},
|
||||||
|
curriedLabels: []string{"method"},
|
||||||
|
ok: true,
|
||||||
|
},
|
||||||
|
"supported label as const and curry with unsupported as var": {
|
||||||
|
varLabels: []string{"foo"},
|
||||||
|
constLabels: []string{"code"},
|
||||||
|
curriedLabels: []string{"method"},
|
||||||
|
ok: false,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for name, sc := range scenarios {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
constLabels := prometheus.Labels{}
|
||||||
|
for _, l := range sc.constLabels {
|
||||||
|
constLabels[l] = "dummy"
|
||||||
|
}
|
||||||
|
c := prometheus.NewCounterVec(
|
||||||
|
prometheus.CounterOpts{
|
||||||
|
Name: "c",
|
||||||
|
Help: "c help",
|
||||||
|
ConstLabels: constLabels,
|
||||||
|
},
|
||||||
|
append(sc.varLabels, sc.curriedLabels...),
|
||||||
|
)
|
||||||
|
o := prometheus.ObserverVec(prometheus.NewHistogramVec(
|
||||||
|
prometheus.HistogramOpts{
|
||||||
|
Name: "c",
|
||||||
|
Help: "c help",
|
||||||
|
ConstLabels: constLabels,
|
||||||
|
},
|
||||||
|
append(sc.varLabels, sc.curriedLabels...),
|
||||||
|
))
|
||||||
|
for _, l := range sc.curriedLabels {
|
||||||
|
c = c.MustCurryWith(prometheus.Labels{l: "dummy"})
|
||||||
|
o = o.MustCurryWith(prometheus.Labels{l: "dummy"})
|
||||||
|
}
|
||||||
|
|
||||||
|
func() {
|
||||||
|
defer func() {
|
||||||
|
if err := recover(); err != nil {
|
||||||
|
if sc.ok {
|
||||||
|
t.Error("unexpected panic:", err)
|
||||||
|
}
|
||||||
|
} else if !sc.ok {
|
||||||
|
t.Error("expected panic")
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
InstrumentHandlerCounter(c, nil)
|
||||||
|
}()
|
||||||
|
func() {
|
||||||
|
defer func() {
|
||||||
|
if err := recover(); err != nil {
|
||||||
|
if sc.ok {
|
||||||
|
t.Error("unexpected panic:", err)
|
||||||
|
}
|
||||||
|
} else if !sc.ok {
|
||||||
|
t.Error("expected panic")
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
InstrumentHandlerDuration(o, nil)
|
||||||
|
}()
|
||||||
|
if sc.ok {
|
||||||
|
// Test if wantCode and wantMethod were detected correctly.
|
||||||
|
var wantCode, wantMethod bool
|
||||||
|
for _, l := range sc.varLabels {
|
||||||
|
if l == "code" {
|
||||||
|
wantCode = true
|
||||||
|
}
|
||||||
|
if l == "method" {
|
||||||
|
wantMethod = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
gotCode, gotMethod := checkLabels(c)
|
||||||
|
if gotCode != wantCode {
|
||||||
|
t.Errorf("wanted code=%t for counter, got code=%t", wantCode, gotCode)
|
||||||
|
}
|
||||||
|
if gotMethod != wantMethod {
|
||||||
|
t.Errorf("wanted method=%t for counter, got method=%t", wantMethod, gotMethod)
|
||||||
|
}
|
||||||
|
gotCode, gotMethod = checkLabels(o)
|
||||||
|
if gotCode != wantCode {
|
||||||
|
t.Errorf("wanted code=%t for observer, got code=%t", wantCode, gotCode)
|
||||||
|
}
|
||||||
|
if gotMethod != wantMethod {
|
||||||
|
t.Errorf("wanted method=%t for observer, got method=%t", wantMethod, gotMethod)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestMiddlewareAPI(t *testing.T) {
|
func TestMiddlewareAPI(t *testing.T) {
|
||||||
reg := prometheus.NewRegistry()
|
reg := prometheus.NewRegistry()
|
||||||
|
|
||||||
|
@ -159,26 +315,15 @@ func ExampleInstrumentHandlerDuration() {
|
||||||
[]string{"code", "method"},
|
[]string{"code", "method"},
|
||||||
)
|
)
|
||||||
|
|
||||||
// pushVec and pullVec are partitioned by the HTTP method and use custom
|
// duration is partitioned by the HTTP method and handler. It uses custom
|
||||||
// buckets based on the expected request duration. ConstLabels are used
|
// buckets based on the expected request duration.
|
||||||
// to set a handler label to mark pushVec as tracking the durations for
|
duration := prometheus.NewHistogramVec(
|
||||||
// pushes and pullVec as tracking the durations for pulls. Note that
|
prometheus.HistogramOpts{
|
||||||
// Name, Help, and Buckets need to be the same for consistency, so we
|
Name: "request_duration_seconds",
|
||||||
// use the same HistogramOpts after just modifying the ConstLabels.
|
Help: "A histogram of latencies for requests.",
|
||||||
histogramOpts := prometheus.HistogramOpts{
|
Buckets: []float64{.25, .5, 1, 2.5, 5, 10},
|
||||||
Name: "request_duration_seconds",
|
},
|
||||||
Help: "A histogram of latencies for requests.",
|
[]string{"handler", "method"},
|
||||||
Buckets: []float64{.25, .5, 1, 2.5, 5, 10},
|
|
||||||
ConstLabels: prometheus.Labels{"handler": "push"},
|
|
||||||
}
|
|
||||||
pushVec := prometheus.NewHistogramVec(
|
|
||||||
histogramOpts,
|
|
||||||
[]string{"method"},
|
|
||||||
)
|
|
||||||
histogramOpts.ConstLabels = prometheus.Labels{"handler": "pull"}
|
|
||||||
pullVec := prometheus.NewHistogramVec(
|
|
||||||
histogramOpts,
|
|
||||||
[]string{"method"},
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// responseSize has no labels, making it a zero-dimensional
|
// responseSize has no labels, making it a zero-dimensional
|
||||||
|
@ -201,23 +346,20 @@ func ExampleInstrumentHandlerDuration() {
|
||||||
})
|
})
|
||||||
|
|
||||||
// Register all of the metrics in the standard registry.
|
// Register all of the metrics in the standard registry.
|
||||||
prometheus.MustRegister(inFlightGauge, counter, pullVec, pushVec, responseSize)
|
prometheus.MustRegister(inFlightGauge, counter, duration, responseSize)
|
||||||
|
|
||||||
// Wrap the pushHandler with our shared middleware, but use the
|
// Instrument the handlers with all the metrics, injecting the "handler"
|
||||||
// endpoint-specific pushVec with InstrumentHandlerDuration.
|
// label by currying.
|
||||||
pushChain := InstrumentHandlerInFlight(inFlightGauge,
|
pushChain := InstrumentHandlerInFlight(inFlightGauge,
|
||||||
InstrumentHandlerCounter(counter,
|
InstrumentHandlerDuration(duration.MustCurryWith(prometheus.Labels{"handler": "push"}),
|
||||||
InstrumentHandlerDuration(pushVec,
|
InstrumentHandlerCounter(counter,
|
||||||
InstrumentHandlerResponseSize(responseSize, pushHandler),
|
InstrumentHandlerResponseSize(responseSize, pushHandler),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
// Wrap the pushHandler with the shared middleware, but use the
|
|
||||||
// endpoint-specific pullVec with InstrumentHandlerDuration.
|
|
||||||
pullChain := InstrumentHandlerInFlight(inFlightGauge,
|
pullChain := InstrumentHandlerInFlight(inFlightGauge,
|
||||||
InstrumentHandlerCounter(counter,
|
InstrumentHandlerDuration(duration.MustCurryWith(prometheus.Labels{"handler": "pull"}),
|
||||||
InstrumentHandlerDuration(pullVec,
|
InstrumentHandlerCounter(counter,
|
||||||
InstrumentHandlerResponseSize(responseSize, pullHandler),
|
InstrumentHandlerResponseSize(responseSize, pullHandler),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|
|
@ -101,23 +101,16 @@ type SummaryOpts struct {
|
||||||
// string.
|
// string.
|
||||||
Help string
|
Help string
|
||||||
|
|
||||||
// ConstLabels are used to attach fixed labels to this
|
// ConstLabels are used to attach fixed labels to this metric. Metrics
|
||||||
// Summary. Summaries with the same fully-qualified name must have the
|
// with the same fully-qualified name must have the same label names in
|
||||||
// same label names in their ConstLabels.
|
// their ConstLabels.
|
||||||
//
|
//
|
||||||
// Note that in most cases, labels have a value that varies during the
|
// ConstLabels are only used rarely. In particular, do not use them to
|
||||||
// lifetime of a process. Those labels are usually managed with a
|
// attach the same labels to all your metrics. Those use cases are
|
||||||
// SummaryVec. ConstLabels serve only special purposes. One is for the
|
// better covered by target labels set by the scraping Prometheus
|
||||||
// special case where the value of a label does not change during the
|
// server, or by one specific metric (e.g. a build_info or a
|
||||||
// lifetime of a process, e.g. if the revision of the running binary is
|
// machine_role metric). See also
|
||||||
// put into a label. Another, more advanced purpose is if more than one
|
// https://prometheus.io/docs/instrumenting/writing_exporters/#target-labels,-not-static-scraped-labels
|
||||||
// Collector needs to collect Summaries with the same fully-qualified
|
|
||||||
// name. In that case, those Summaries must differ in the values of
|
|
||||||
// their ConstLabels. See the Collector examples.
|
|
||||||
//
|
|
||||||
// If the value of a label never changes (not even between binaries),
|
|
||||||
// that label most likely should not be a label at all (but part of the
|
|
||||||
// metric name).
|
|
||||||
ConstLabels Labels
|
ConstLabels Labels
|
||||||
|
|
||||||
// Objectives defines the quantile rank estimates with their respective
|
// Objectives defines the quantile rank estimates with their respective
|
||||||
|
@ -433,13 +426,13 @@ func NewSummaryVec(opts SummaryOpts, labelNames []string) *SummaryVec {
|
||||||
//
|
//
|
||||||
// Keeping the Summary for later use is possible (and should be considered if
|
// Keeping the Summary for later use is possible (and should be considered if
|
||||||
// performance is critical), but keep in mind that Reset, DeleteLabelValues and
|
// performance is critical), but keep in mind that Reset, DeleteLabelValues and
|
||||||
// Delete can be used to delete the Summary from the SummaryVec. In that case, the
|
// Delete can be used to delete the Summary from the SummaryVec. In that case,
|
||||||
// Summary will still exist, but it will not be exported anymore, even if a
|
// the Summary will still exist, but it will not be exported anymore, even if a
|
||||||
// Summary with the same label values is created later. See also the CounterVec
|
// Summary with the same label values is created later. See also the CounterVec
|
||||||
// example.
|
// example.
|
||||||
//
|
//
|
||||||
// An error is returned if the number of label values is not the same as the
|
// An error is returned if the number of label values is not the same as the
|
||||||
// number of VariableLabels in Desc.
|
// number of VariableLabels in Desc (minus any curried labels).
|
||||||
//
|
//
|
||||||
// Note that for more than one label value, this method is prone to mistakes
|
// Note that for more than one label value, this method is prone to mistakes
|
||||||
// caused by an incorrect order of arguments. Consider GetMetricWith(Labels) as
|
// caused by an incorrect order of arguments. Consider GetMetricWith(Labels) as
|
||||||
|
@ -447,8 +440,8 @@ func NewSummaryVec(opts SummaryOpts, labelNames []string) *SummaryVec {
|
||||||
// latter has a much more readable (albeit more verbose) syntax, but it comes
|
// latter has a much more readable (albeit more verbose) syntax, but it comes
|
||||||
// with a performance overhead (for creating and processing the Labels map).
|
// with a performance overhead (for creating and processing the Labels map).
|
||||||
// See also the GaugeVec example.
|
// See also the GaugeVec example.
|
||||||
func (m *SummaryVec) GetMetricWithLabelValues(lvs ...string) (Observer, error) {
|
func (v *SummaryVec) GetMetricWithLabelValues(lvs ...string) (Observer, error) {
|
||||||
metric, err := m.metricVec.getMetricWithLabelValues(lvs...)
|
metric, err := v.metricVec.getMetricWithLabelValues(lvs...)
|
||||||
if metric != nil {
|
if metric != nil {
|
||||||
return metric.(Observer), err
|
return metric.(Observer), err
|
||||||
}
|
}
|
||||||
|
@ -462,13 +455,13 @@ func (m *SummaryVec) GetMetricWithLabelValues(lvs ...string) (Observer, error) {
|
||||||
// the same as for GetMetricWithLabelValues.
|
// the same as for GetMetricWithLabelValues.
|
||||||
//
|
//
|
||||||
// An error is returned if the number and names of the Labels are inconsistent
|
// An error is returned if the number and names of the Labels are inconsistent
|
||||||
// with those of the VariableLabels in Desc.
|
// with those of the VariableLabels in Desc (minus any curried labels).
|
||||||
//
|
//
|
||||||
// This method is used for the same purpose as
|
// This method is used for the same purpose as
|
||||||
// GetMetricWithLabelValues(...string). See there for pros and cons of the two
|
// GetMetricWithLabelValues(...string). See there for pros and cons of the two
|
||||||
// methods.
|
// methods.
|
||||||
func (m *SummaryVec) GetMetricWith(labels Labels) (Observer, error) {
|
func (v *SummaryVec) GetMetricWith(labels Labels) (Observer, error) {
|
||||||
metric, err := m.metricVec.getMetricWith(labels)
|
metric, err := v.metricVec.getMetricWith(labels)
|
||||||
if metric != nil {
|
if metric != nil {
|
||||||
return metric.(Observer), err
|
return metric.(Observer), err
|
||||||
}
|
}
|
||||||
|
@ -476,18 +469,57 @@ func (m *SummaryVec) GetMetricWith(labels Labels) (Observer, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// WithLabelValues works as GetMetricWithLabelValues, but panics where
|
// WithLabelValues works as GetMetricWithLabelValues, but panics where
|
||||||
// GetMetricWithLabelValues would have returned an error. By not returning an
|
// GetMetricWithLabelValues would have returned an error. Not returning an
|
||||||
// error, WithLabelValues allows shortcuts like
|
// error allows shortcuts like
|
||||||
// myVec.WithLabelValues("404", "GET").Observe(42.21)
|
// myVec.WithLabelValues("404", "GET").Observe(42.21)
|
||||||
func (m *SummaryVec) WithLabelValues(lvs ...string) Observer {
|
func (v *SummaryVec) WithLabelValues(lvs ...string) Observer {
|
||||||
return m.metricVec.withLabelValues(lvs...).(Observer)
|
s, err := v.GetMetricWithLabelValues(lvs...)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return s
|
||||||
}
|
}
|
||||||
|
|
||||||
// With works as GetMetricWith, but panics where GetMetricWithLabels would have
|
// With works as GetMetricWith, but panics where GetMetricWithLabels would have
|
||||||
// returned an error. By not returning an error, With allows shortcuts like
|
// returned an error. Not returning an error allows shortcuts like
|
||||||
// myVec.With(Labels{"code": "404", "method": "GET"}).Observe(42.21)
|
// myVec.With(prometheus.Labels{"code": "404", "method": "GET"}).Observe(42.21)
|
||||||
func (m *SummaryVec) With(labels Labels) Observer {
|
func (v *SummaryVec) With(labels Labels) Observer {
|
||||||
return m.metricVec.with(labels).(Observer)
|
s, err := v.GetMetricWith(labels)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// CurryWith returns a vector curried with the provided labels, i.e. the
|
||||||
|
// returned vector has those labels pre-set for all labeled operations performed
|
||||||
|
// on it. The cardinality of the curried vector is reduced accordingly. The
|
||||||
|
// order of the remaining labels stays the same (just with the curried labels
|
||||||
|
// taken out of the sequence – which is relevant for the
|
||||||
|
// (GetMetric)WithLabelValues methods). It is possible to curry a curried
|
||||||
|
// vector, but only with labels not yet used for currying before.
|
||||||
|
//
|
||||||
|
// The metrics contained in the SummaryVec are shared between the curried and
|
||||||
|
// uncurried vectors. They are just accessed differently. Curried and uncurried
|
||||||
|
// vectors behave identically in terms of collection. Only one must be
|
||||||
|
// registered with a given registry (usually the uncurried version). The Reset
|
||||||
|
// method deletes all metrics, even if called on a curried vector.
|
||||||
|
func (v *SummaryVec) CurryWith(labels Labels) (ObserverVec, error) {
|
||||||
|
vec, err := v.curryWith(labels)
|
||||||
|
if vec != nil {
|
||||||
|
return &SummaryVec{vec}, err
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// MustCurryWith works as CurryWith but panics where CurryWith would have
|
||||||
|
// returned an error.
|
||||||
|
func (v *SummaryVec) MustCurryWith(labels Labels) ObserverVec {
|
||||||
|
vec, err := v.CurryWith(labels)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return vec
|
||||||
}
|
}
|
||||||
|
|
||||||
type constSummary struct {
|
type constSummary struct {
|
||||||
|
|
|
@ -23,88 +23,31 @@ import (
|
||||||
// metricVec is a Collector to bundle metrics of the same name that differ in
|
// metricVec is a Collector to bundle metrics of the same name that differ in
|
||||||
// their label values. metricVec is not used directly (and therefore
|
// their label values. metricVec is not used directly (and therefore
|
||||||
// unexported). It is used as a building block for implementations of vectors of
|
// unexported). It is used as a building block for implementations of vectors of
|
||||||
// a given metric type, like GaugeVec, CounterVec, SummaryVec, HistogramVec, and
|
// a given metric type, like GaugeVec, CounterVec, SummaryVec, and HistogramVec.
|
||||||
// UntypedVec.
|
// It also handles label currying. It uses basicMetricVec internally.
|
||||||
type metricVec struct {
|
type metricVec struct {
|
||||||
mtx sync.RWMutex // Protects the children.
|
*metricMap
|
||||||
children map[uint64][]metricWithLabelValues
|
|
||||||
desc *Desc
|
|
||||||
|
|
||||||
newMetric func(labelValues ...string) Metric
|
curry []curriedLabelValue
|
||||||
hashAdd func(h uint64, s string) uint64 // replace hash function for testing collision handling
|
|
||||||
|
// hashAdd and hashAddByte can be replaced for testing collision handling.
|
||||||
|
hashAdd func(h uint64, s string) uint64
|
||||||
hashAddByte func(h uint64, b byte) uint64
|
hashAddByte func(h uint64, b byte) uint64
|
||||||
}
|
}
|
||||||
|
|
||||||
// newMetricVec returns an initialized metricVec.
|
// newMetricVec returns an initialized metricVec.
|
||||||
func newMetricVec(desc *Desc, newMetric func(lvs ...string) Metric) *metricVec {
|
func newMetricVec(desc *Desc, newMetric func(lvs ...string) Metric) *metricVec {
|
||||||
return &metricVec{
|
return &metricVec{
|
||||||
children: map[uint64][]metricWithLabelValues{},
|
metricMap: &metricMap{
|
||||||
desc: desc,
|
metrics: map[uint64][]metricWithLabelValues{},
|
||||||
newMetric: newMetric,
|
desc: desc,
|
||||||
|
newMetric: newMetric,
|
||||||
|
},
|
||||||
hashAdd: hashAdd,
|
hashAdd: hashAdd,
|
||||||
hashAddByte: hashAddByte,
|
hashAddByte: hashAddByte,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// metricWithLabelValues provides the metric and its label values for
|
|
||||||
// disambiguation on hash collision.
|
|
||||||
type metricWithLabelValues struct {
|
|
||||||
values []string
|
|
||||||
metric Metric
|
|
||||||
}
|
|
||||||
|
|
||||||
// Describe implements Collector. The length of the returned slice
|
|
||||||
// is always one.
|
|
||||||
func (m *metricVec) Describe(ch chan<- *Desc) {
|
|
||||||
ch <- m.desc
|
|
||||||
}
|
|
||||||
|
|
||||||
// Collect implements Collector.
|
|
||||||
func (m *metricVec) Collect(ch chan<- Metric) {
|
|
||||||
m.mtx.RLock()
|
|
||||||
defer m.mtx.RUnlock()
|
|
||||||
|
|
||||||
for _, metrics := range m.children {
|
|
||||||
for _, metric := range metrics {
|
|
||||||
ch <- metric.metric
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *metricVec) getMetricWithLabelValues(lvs ...string) (Metric, error) {
|
|
||||||
h, err := m.hashLabelValues(lvs)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return m.getOrCreateMetricWithLabelValues(h, lvs), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *metricVec) getMetricWith(labels Labels) (Metric, error) {
|
|
||||||
h, err := m.hashLabels(labels)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return m.getOrCreateMetricWithLabels(h, labels), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *metricVec) withLabelValues(lvs ...string) Metric {
|
|
||||||
metric, err := m.getMetricWithLabelValues(lvs...)
|
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
return metric
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *metricVec) with(labels Labels) Metric {
|
|
||||||
metric, err := m.getMetricWith(labels)
|
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
return metric
|
|
||||||
}
|
|
||||||
|
|
||||||
// DeleteLabelValues removes the metric where the variable labels are the same
|
// DeleteLabelValues removes the metric where the variable labels are the same
|
||||||
// as those passed in as labels (same order as the VariableLabels in Desc). It
|
// as those passed in as labels (same order as the VariableLabels in Desc). It
|
||||||
// returns true if a metric was deleted.
|
// returns true if a metric was deleted.
|
||||||
|
@ -121,14 +64,12 @@ func (m *metricVec) with(labels Labels) Metric {
|
||||||
// with a performance overhead (for creating and processing the Labels map).
|
// with a performance overhead (for creating and processing the Labels map).
|
||||||
// See also the CounterVec example.
|
// See also the CounterVec example.
|
||||||
func (m *metricVec) DeleteLabelValues(lvs ...string) bool {
|
func (m *metricVec) DeleteLabelValues(lvs ...string) bool {
|
||||||
m.mtx.Lock()
|
|
||||||
defer m.mtx.Unlock()
|
|
||||||
|
|
||||||
h, err := m.hashLabelValues(lvs)
|
h, err := m.hashLabelValues(lvs)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
return m.deleteByHashWithLabelValues(h, lvs)
|
|
||||||
|
return m.metricMap.deleteByHashWithLabelValues(h, lvs, m.curry)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete deletes the metric where the variable labels are the same as those
|
// Delete deletes the metric where the variable labels are the same as those
|
||||||
|
@ -142,35 +83,190 @@ func (m *metricVec) DeleteLabelValues(lvs ...string) bool {
|
||||||
// This method is used for the same purpose as DeleteLabelValues(...string). See
|
// This method is used for the same purpose as DeleteLabelValues(...string). See
|
||||||
// there for pros and cons of the two methods.
|
// there for pros and cons of the two methods.
|
||||||
func (m *metricVec) Delete(labels Labels) bool {
|
func (m *metricVec) Delete(labels Labels) bool {
|
||||||
m.mtx.Lock()
|
|
||||||
defer m.mtx.Unlock()
|
|
||||||
|
|
||||||
h, err := m.hashLabels(labels)
|
h, err := m.hashLabels(labels)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
return m.deleteByHashWithLabels(h, labels)
|
return m.metricMap.deleteByHashWithLabels(h, labels, m.curry)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *metricVec) curryWith(labels Labels) (*metricVec, error) {
|
||||||
|
var (
|
||||||
|
newCurry []curriedLabelValue
|
||||||
|
oldCurry = m.curry
|
||||||
|
iCurry int
|
||||||
|
)
|
||||||
|
for i, label := range m.desc.variableLabels {
|
||||||
|
val, ok := labels[label]
|
||||||
|
if iCurry < len(oldCurry) && oldCurry[iCurry].index == i {
|
||||||
|
if ok {
|
||||||
|
return nil, fmt.Errorf("label name %q is already curried", label)
|
||||||
|
}
|
||||||
|
newCurry = append(newCurry, oldCurry[iCurry])
|
||||||
|
iCurry++
|
||||||
|
} else {
|
||||||
|
if !ok {
|
||||||
|
continue // Label stays uncurried.
|
||||||
|
}
|
||||||
|
newCurry = append(newCurry, curriedLabelValue{i, val})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if l := len(oldCurry) + len(labels) - len(newCurry); l > 0 {
|
||||||
|
return nil, fmt.Errorf("%d unknown label(s) found during currying", l)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &metricVec{
|
||||||
|
metricMap: m.metricMap,
|
||||||
|
curry: newCurry,
|
||||||
|
hashAdd: m.hashAdd,
|
||||||
|
hashAddByte: m.hashAddByte,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *metricVec) getMetricWithLabelValues(lvs ...string) (Metric, error) {
|
||||||
|
h, err := m.hashLabelValues(lvs)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return m.metricMap.getOrCreateMetricWithLabelValues(h, lvs, m.curry), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *metricVec) getMetricWith(labels Labels) (Metric, error) {
|
||||||
|
h, err := m.hashLabels(labels)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return m.metricMap.getOrCreateMetricWithLabels(h, labels, m.curry), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *metricVec) hashLabelValues(vals []string) (uint64, error) {
|
||||||
|
if err := validateLabelValues(vals, len(m.desc.variableLabels)-len(m.curry)); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
h = hashNew()
|
||||||
|
curry = m.curry
|
||||||
|
iVals, iCurry int
|
||||||
|
)
|
||||||
|
for i := 0; i < len(m.desc.variableLabels); i++ {
|
||||||
|
if iCurry < len(curry) && curry[iCurry].index == i {
|
||||||
|
h = m.hashAdd(h, curry[iCurry].value)
|
||||||
|
iCurry++
|
||||||
|
} else {
|
||||||
|
h = m.hashAdd(h, vals[iVals])
|
||||||
|
iVals++
|
||||||
|
}
|
||||||
|
h = m.hashAddByte(h, model.SeparatorByte)
|
||||||
|
}
|
||||||
|
return h, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *metricVec) hashLabels(labels Labels) (uint64, error) {
|
||||||
|
if err := validateValuesInLabels(labels, len(m.desc.variableLabels)-len(m.curry)); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
h = hashNew()
|
||||||
|
curry = m.curry
|
||||||
|
iCurry int
|
||||||
|
)
|
||||||
|
for i, label := range m.desc.variableLabels {
|
||||||
|
val, ok := labels[label]
|
||||||
|
if iCurry < len(curry) && curry[iCurry].index == i {
|
||||||
|
if ok {
|
||||||
|
return 0, fmt.Errorf("label name %q is already curried", label)
|
||||||
|
}
|
||||||
|
h = m.hashAdd(h, curry[iCurry].value)
|
||||||
|
iCurry++
|
||||||
|
} else {
|
||||||
|
if !ok {
|
||||||
|
return 0, fmt.Errorf("label name %q missing in label map", label)
|
||||||
|
}
|
||||||
|
h = m.hashAdd(h, val)
|
||||||
|
}
|
||||||
|
h = m.hashAddByte(h, model.SeparatorByte)
|
||||||
|
}
|
||||||
|
return h, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// metricWithLabelValues provides the metric and its label values for
|
||||||
|
// disambiguation on hash collision.
|
||||||
|
type metricWithLabelValues struct {
|
||||||
|
values []string
|
||||||
|
metric Metric
|
||||||
|
}
|
||||||
|
|
||||||
|
// curriedLabelValue sets the curried value for a label at the given index.
|
||||||
|
type curriedLabelValue struct {
|
||||||
|
index int
|
||||||
|
value string
|
||||||
|
}
|
||||||
|
|
||||||
|
// metricMap is a helper for metricVec and shared between differently curried
|
||||||
|
// metricVecs.
|
||||||
|
type metricMap struct {
|
||||||
|
mtx sync.RWMutex // Protects metrics.
|
||||||
|
metrics map[uint64][]metricWithLabelValues
|
||||||
|
desc *Desc
|
||||||
|
newMetric func(labelValues ...string) Metric
|
||||||
|
}
|
||||||
|
|
||||||
|
// Describe implements Collector. It will send exactly one Desc to the provided
|
||||||
|
// channel.
|
||||||
|
func (m *metricMap) Describe(ch chan<- *Desc) {
|
||||||
|
ch <- m.desc
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collect implements Collector.
|
||||||
|
func (m *metricMap) Collect(ch chan<- Metric) {
|
||||||
|
m.mtx.RLock()
|
||||||
|
defer m.mtx.RUnlock()
|
||||||
|
|
||||||
|
for _, metrics := range m.metrics {
|
||||||
|
for _, metric := range metrics {
|
||||||
|
ch <- metric.metric
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset deletes all metrics in this vector.
|
||||||
|
func (m *metricMap) Reset() {
|
||||||
|
m.mtx.Lock()
|
||||||
|
defer m.mtx.Unlock()
|
||||||
|
|
||||||
|
for h := range m.metrics {
|
||||||
|
delete(m.metrics, h)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// deleteByHashWithLabelValues removes the metric from the hash bucket h. If
|
// deleteByHashWithLabelValues removes the metric from the hash bucket h. If
|
||||||
// there are multiple matches in the bucket, use lvs to select a metric and
|
// there are multiple matches in the bucket, use lvs to select a metric and
|
||||||
// remove only that metric.
|
// remove only that metric.
|
||||||
func (m *metricVec) deleteByHashWithLabelValues(h uint64, lvs []string) bool {
|
func (m *metricMap) deleteByHashWithLabelValues(
|
||||||
metrics, ok := m.children[h]
|
h uint64, lvs []string, curry []curriedLabelValue,
|
||||||
|
) bool {
|
||||||
|
m.mtx.Lock()
|
||||||
|
defer m.mtx.Unlock()
|
||||||
|
|
||||||
|
metrics, ok := m.metrics[h]
|
||||||
if !ok {
|
if !ok {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
i := m.findMetricWithLabelValues(metrics, lvs)
|
i := findMetricWithLabelValues(metrics, lvs, curry)
|
||||||
if i >= len(metrics) {
|
if i >= len(metrics) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(metrics) > 1 {
|
if len(metrics) > 1 {
|
||||||
m.children[h] = append(metrics[:i], metrics[i+1:]...)
|
m.metrics[h] = append(metrics[:i], metrics[i+1:]...)
|
||||||
} else {
|
} else {
|
||||||
delete(m.children, h)
|
delete(m.metrics, h)
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
@ -178,71 +274,35 @@ func (m *metricVec) deleteByHashWithLabelValues(h uint64, lvs []string) bool {
|
||||||
// deleteByHashWithLabels removes the metric from the hash bucket h. If there
|
// deleteByHashWithLabels removes the metric from the hash bucket h. If there
|
||||||
// are multiple matches in the bucket, use lvs to select a metric and remove
|
// are multiple matches in the bucket, use lvs to select a metric and remove
|
||||||
// only that metric.
|
// only that metric.
|
||||||
func (m *metricVec) deleteByHashWithLabels(h uint64, labels Labels) bool {
|
func (m *metricMap) deleteByHashWithLabels(
|
||||||
metrics, ok := m.children[h]
|
h uint64, labels Labels, curry []curriedLabelValue,
|
||||||
|
) bool {
|
||||||
|
metrics, ok := m.metrics[h]
|
||||||
if !ok {
|
if !ok {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
i := m.findMetricWithLabels(metrics, labels)
|
i := findMetricWithLabels(m.desc, metrics, labels, curry)
|
||||||
if i >= len(metrics) {
|
if i >= len(metrics) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(metrics) > 1 {
|
if len(metrics) > 1 {
|
||||||
m.children[h] = append(metrics[:i], metrics[i+1:]...)
|
m.metrics[h] = append(metrics[:i], metrics[i+1:]...)
|
||||||
} else {
|
} else {
|
||||||
delete(m.children, h)
|
delete(m.metrics, h)
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reset deletes all metrics in this vector.
|
|
||||||
func (m *metricVec) Reset() {
|
|
||||||
m.mtx.Lock()
|
|
||||||
defer m.mtx.Unlock()
|
|
||||||
|
|
||||||
for h := range m.children {
|
|
||||||
delete(m.children, h)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *metricVec) hashLabelValues(vals []string) (uint64, error) {
|
|
||||||
if err := validateLabelValues(vals, len(m.desc.variableLabels)); err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
h := hashNew()
|
|
||||||
for _, val := range vals {
|
|
||||||
h = m.hashAdd(h, val)
|
|
||||||
h = m.hashAddByte(h, model.SeparatorByte)
|
|
||||||
}
|
|
||||||
return h, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *metricVec) hashLabels(labels Labels) (uint64, error) {
|
|
||||||
if err := validateValuesInLabels(labels, len(m.desc.variableLabels)); err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
h := hashNew()
|
|
||||||
for _, label := range m.desc.variableLabels {
|
|
||||||
val, ok := labels[label]
|
|
||||||
if !ok {
|
|
||||||
return 0, fmt.Errorf("label name %q missing in label map", label)
|
|
||||||
}
|
|
||||||
h = m.hashAdd(h, val)
|
|
||||||
h = m.hashAddByte(h, model.SeparatorByte)
|
|
||||||
}
|
|
||||||
return h, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// getOrCreateMetricWithLabelValues retrieves the metric by hash and label value
|
// getOrCreateMetricWithLabelValues retrieves the metric by hash and label value
|
||||||
// or creates it and returns the new one.
|
// or creates it and returns the new one.
|
||||||
//
|
//
|
||||||
// This function holds the mutex.
|
// This function holds the mutex.
|
||||||
func (m *metricVec) getOrCreateMetricWithLabelValues(hash uint64, lvs []string) Metric {
|
func (m *metricMap) getOrCreateMetricWithLabelValues(
|
||||||
|
hash uint64, lvs []string, curry []curriedLabelValue,
|
||||||
|
) Metric {
|
||||||
m.mtx.RLock()
|
m.mtx.RLock()
|
||||||
metric, ok := m.getMetricWithHashAndLabelValues(hash, lvs)
|
metric, ok := m.getMetricWithHashAndLabelValues(hash, lvs, curry)
|
||||||
m.mtx.RUnlock()
|
m.mtx.RUnlock()
|
||||||
if ok {
|
if ok {
|
||||||
return metric
|
return metric
|
||||||
|
@ -250,13 +310,11 @@ func (m *metricVec) getOrCreateMetricWithLabelValues(hash uint64, lvs []string)
|
||||||
|
|
||||||
m.mtx.Lock()
|
m.mtx.Lock()
|
||||||
defer m.mtx.Unlock()
|
defer m.mtx.Unlock()
|
||||||
metric, ok = m.getMetricWithHashAndLabelValues(hash, lvs)
|
metric, ok = m.getMetricWithHashAndLabelValues(hash, lvs, curry)
|
||||||
if !ok {
|
if !ok {
|
||||||
// Copy to avoid allocation in case wo don't go down this code path.
|
inlinedLVs := inlineLabelValues(lvs, curry)
|
||||||
copiedLVs := make([]string, len(lvs))
|
metric = m.newMetric(inlinedLVs...)
|
||||||
copy(copiedLVs, lvs)
|
m.metrics[hash] = append(m.metrics[hash], metricWithLabelValues{values: inlinedLVs, metric: metric})
|
||||||
metric = m.newMetric(copiedLVs...)
|
|
||||||
m.children[hash] = append(m.children[hash], metricWithLabelValues{values: copiedLVs, metric: metric})
|
|
||||||
}
|
}
|
||||||
return metric
|
return metric
|
||||||
}
|
}
|
||||||
|
@ -265,9 +323,11 @@ func (m *metricVec) getOrCreateMetricWithLabelValues(hash uint64, lvs []string)
|
||||||
// or creates it and returns the new one.
|
// or creates it and returns the new one.
|
||||||
//
|
//
|
||||||
// This function holds the mutex.
|
// This function holds the mutex.
|
||||||
func (m *metricVec) getOrCreateMetricWithLabels(hash uint64, labels Labels) Metric {
|
func (m *metricMap) getOrCreateMetricWithLabels(
|
||||||
|
hash uint64, labels Labels, curry []curriedLabelValue,
|
||||||
|
) Metric {
|
||||||
m.mtx.RLock()
|
m.mtx.RLock()
|
||||||
metric, ok := m.getMetricWithHashAndLabels(hash, labels)
|
metric, ok := m.getMetricWithHashAndLabels(hash, labels, curry)
|
||||||
m.mtx.RUnlock()
|
m.mtx.RUnlock()
|
||||||
if ok {
|
if ok {
|
||||||
return metric
|
return metric
|
||||||
|
@ -275,21 +335,23 @@ func (m *metricVec) getOrCreateMetricWithLabels(hash uint64, labels Labels) Metr
|
||||||
|
|
||||||
m.mtx.Lock()
|
m.mtx.Lock()
|
||||||
defer m.mtx.Unlock()
|
defer m.mtx.Unlock()
|
||||||
metric, ok = m.getMetricWithHashAndLabels(hash, labels)
|
metric, ok = m.getMetricWithHashAndLabels(hash, labels, curry)
|
||||||
if !ok {
|
if !ok {
|
||||||
lvs := m.extractLabelValues(labels)
|
lvs := extractLabelValues(m.desc, labels, curry)
|
||||||
metric = m.newMetric(lvs...)
|
metric = m.newMetric(lvs...)
|
||||||
m.children[hash] = append(m.children[hash], metricWithLabelValues{values: lvs, metric: metric})
|
m.metrics[hash] = append(m.metrics[hash], metricWithLabelValues{values: lvs, metric: metric})
|
||||||
}
|
}
|
||||||
return metric
|
return metric
|
||||||
}
|
}
|
||||||
|
|
||||||
// getMetricWithHashAndLabelValues gets a metric while handling possible
|
// getMetricWithHashAndLabelValues gets a metric while handling possible
|
||||||
// collisions in the hash space. Must be called while holding the read mutex.
|
// collisions in the hash space. Must be called while holding the read mutex.
|
||||||
func (m *metricVec) getMetricWithHashAndLabelValues(h uint64, lvs []string) (Metric, bool) {
|
func (m *metricMap) getMetricWithHashAndLabelValues(
|
||||||
metrics, ok := m.children[h]
|
h uint64, lvs []string, curry []curriedLabelValue,
|
||||||
|
) (Metric, bool) {
|
||||||
|
metrics, ok := m.metrics[h]
|
||||||
if ok {
|
if ok {
|
||||||
if i := m.findMetricWithLabelValues(metrics, lvs); i < len(metrics) {
|
if i := findMetricWithLabelValues(metrics, lvs, curry); i < len(metrics) {
|
||||||
return metrics[i].metric, true
|
return metrics[i].metric, true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -298,10 +360,12 @@ func (m *metricVec) getMetricWithHashAndLabelValues(h uint64, lvs []string) (Met
|
||||||
|
|
||||||
// getMetricWithHashAndLabels gets a metric while handling possible collisions in
|
// getMetricWithHashAndLabels gets a metric while handling possible collisions in
|
||||||
// the hash space. Must be called while holding read mutex.
|
// the hash space. Must be called while holding read mutex.
|
||||||
func (m *metricVec) getMetricWithHashAndLabels(h uint64, labels Labels) (Metric, bool) {
|
func (m *metricMap) getMetricWithHashAndLabels(
|
||||||
metrics, ok := m.children[h]
|
h uint64, labels Labels, curry []curriedLabelValue,
|
||||||
|
) (Metric, bool) {
|
||||||
|
metrics, ok := m.metrics[h]
|
||||||
if ok {
|
if ok {
|
||||||
if i := m.findMetricWithLabels(metrics, labels); i < len(metrics) {
|
if i := findMetricWithLabels(m.desc, metrics, labels, curry); i < len(metrics) {
|
||||||
return metrics[i].metric, true
|
return metrics[i].metric, true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -310,9 +374,11 @@ func (m *metricVec) getMetricWithHashAndLabels(h uint64, labels Labels) (Metric,
|
||||||
|
|
||||||
// findMetricWithLabelValues returns the index of the matching metric or
|
// findMetricWithLabelValues returns the index of the matching metric or
|
||||||
// len(metrics) if not found.
|
// len(metrics) if not found.
|
||||||
func (m *metricVec) findMetricWithLabelValues(metrics []metricWithLabelValues, lvs []string) int {
|
func findMetricWithLabelValues(
|
||||||
|
metrics []metricWithLabelValues, lvs []string, curry []curriedLabelValue,
|
||||||
|
) int {
|
||||||
for i, metric := range metrics {
|
for i, metric := range metrics {
|
||||||
if m.matchLabelValues(metric.values, lvs) {
|
if matchLabelValues(metric.values, lvs, curry) {
|
||||||
return i
|
return i
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -321,32 +387,51 @@ func (m *metricVec) findMetricWithLabelValues(metrics []metricWithLabelValues, l
|
||||||
|
|
||||||
// findMetricWithLabels returns the index of the matching metric or len(metrics)
|
// findMetricWithLabels returns the index of the matching metric or len(metrics)
|
||||||
// if not found.
|
// if not found.
|
||||||
func (m *metricVec) findMetricWithLabels(metrics []metricWithLabelValues, labels Labels) int {
|
func findMetricWithLabels(
|
||||||
|
desc *Desc, metrics []metricWithLabelValues, labels Labels, curry []curriedLabelValue,
|
||||||
|
) int {
|
||||||
for i, metric := range metrics {
|
for i, metric := range metrics {
|
||||||
if m.matchLabels(metric.values, labels) {
|
if matchLabels(desc, metric.values, labels, curry) {
|
||||||
return i
|
return i
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return len(metrics)
|
return len(metrics)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *metricVec) matchLabelValues(values []string, lvs []string) bool {
|
func matchLabelValues(values []string, lvs []string, curry []curriedLabelValue) bool {
|
||||||
if len(values) != len(lvs) {
|
if len(values) != len(lvs)+len(curry) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
var iLVs, iCurry int
|
||||||
for i, v := range values {
|
for i, v := range values {
|
||||||
if v != lvs[i] {
|
if iCurry < len(curry) && curry[iCurry].index == i {
|
||||||
|
if v != curry[iCurry].value {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
iCurry++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if v != lvs[iLVs] {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
iLVs++
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *metricVec) matchLabels(values []string, labels Labels) bool {
|
func matchLabels(desc *Desc, values []string, labels Labels, curry []curriedLabelValue) bool {
|
||||||
if len(labels) != len(values) {
|
if len(values) != len(labels)+len(curry) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
for i, k := range m.desc.variableLabels {
|
iCurry := 0
|
||||||
|
for i, k := range desc.variableLabels {
|
||||||
|
if iCurry < len(curry) && curry[iCurry].index == i {
|
||||||
|
if values[i] != curry[iCurry].value {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
iCurry++
|
||||||
|
continue
|
||||||
|
}
|
||||||
if values[i] != labels[k] {
|
if values[i] != labels[k] {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
@ -354,10 +439,31 @@ func (m *metricVec) matchLabels(values []string, labels Labels) bool {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *metricVec) extractLabelValues(labels Labels) []string {
|
func extractLabelValues(desc *Desc, labels Labels, curry []curriedLabelValue) []string {
|
||||||
labelValues := make([]string, len(labels))
|
labelValues := make([]string, len(labels)+len(curry))
|
||||||
for i, k := range m.desc.variableLabels {
|
iCurry := 0
|
||||||
|
for i, k := range desc.variableLabels {
|
||||||
|
if iCurry < len(curry) && curry[iCurry].index == i {
|
||||||
|
labelValues[i] = curry[iCurry].value
|
||||||
|
iCurry++
|
||||||
|
continue
|
||||||
|
}
|
||||||
labelValues[i] = labels[k]
|
labelValues[i] = labels[k]
|
||||||
}
|
}
|
||||||
return labelValues
|
return labelValues
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func inlineLabelValues(lvs []string, curry []curriedLabelValue) []string {
|
||||||
|
labelValues := make([]string, len(lvs)+len(curry))
|
||||||
|
var iCurry, iLVs int
|
||||||
|
for i := range labelValues {
|
||||||
|
if iCurry < len(curry) && curry[iCurry].index == i {
|
||||||
|
labelValues[i] = curry[iCurry].value
|
||||||
|
iCurry++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
labelValues[i] = lvs[iLVs]
|
||||||
|
iLVs++
|
||||||
|
}
|
||||||
|
return labelValues
|
||||||
|
}
|
||||||
|
|
|
@ -166,7 +166,7 @@ func testMetricVec(t *testing.T, vec *GaugeVec) {
|
||||||
}
|
}
|
||||||
|
|
||||||
var total int
|
var total int
|
||||||
for _, metrics := range vec.children {
|
for _, metrics := range vec.metricMap.metrics {
|
||||||
for _, metric := range metrics {
|
for _, metric := range metrics {
|
||||||
total++
|
total++
|
||||||
copy(pair[:], metric.values)
|
copy(pair[:], metric.values)
|
||||||
|
@ -201,7 +201,7 @@ func testMetricVec(t *testing.T, vec *GaugeVec) {
|
||||||
|
|
||||||
vec.Reset()
|
vec.Reset()
|
||||||
|
|
||||||
if len(vec.children) > 0 {
|
if len(vec.metricMap.metrics) > 0 {
|
||||||
t.Fatalf("reset failed")
|
t.Fatalf("reset failed")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -239,6 +239,229 @@ func TestCounterVecEndToEndWithCollision(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCurryVec(t *testing.T) {
|
||||||
|
vec := NewCounterVec(
|
||||||
|
CounterOpts{
|
||||||
|
Name: "test",
|
||||||
|
Help: "helpless",
|
||||||
|
},
|
||||||
|
[]string{"one", "two", "three"},
|
||||||
|
)
|
||||||
|
testCurryVec(t, vec)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCurryVecWithCollisions(t *testing.T) {
|
||||||
|
vec := NewCounterVec(
|
||||||
|
CounterOpts{
|
||||||
|
Name: "test",
|
||||||
|
Help: "helpless",
|
||||||
|
},
|
||||||
|
[]string{"one", "two", "three"},
|
||||||
|
)
|
||||||
|
vec.hashAdd = func(h uint64, s string) uint64 { return 1 }
|
||||||
|
vec.hashAddByte = func(h uint64, b byte) uint64 { return 1 }
|
||||||
|
testCurryVec(t, vec)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testCurryVec(t *testing.T, vec *CounterVec) {
|
||||||
|
|
||||||
|
assertMetrics := func(t *testing.T) {
|
||||||
|
n := 0
|
||||||
|
for _, m := range vec.metricMap.metrics {
|
||||||
|
n += len(m)
|
||||||
|
}
|
||||||
|
if n != 2 {
|
||||||
|
t.Error("expected two metrics, got", n)
|
||||||
|
}
|
||||||
|
m := &dto.Metric{}
|
||||||
|
c1, err := vec.GetMetricWithLabelValues("1", "2", "3")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("unexpected error getting metric:", err)
|
||||||
|
}
|
||||||
|
c1.Write(m)
|
||||||
|
if want, got := 1., m.GetCounter().GetValue(); want != got {
|
||||||
|
t.Errorf("want %f as counter value, got %f", want, got)
|
||||||
|
}
|
||||||
|
m.Reset()
|
||||||
|
c2, err := vec.GetMetricWithLabelValues("11", "22", "33")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("unexpected error getting metric:", err)
|
||||||
|
}
|
||||||
|
c2.Write(m)
|
||||||
|
if want, got := 1., m.GetCounter().GetValue(); want != got {
|
||||||
|
t.Errorf("want %f as counter value, got %f", want, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
assertNoMetric := func(t *testing.T) {
|
||||||
|
if n := len(vec.metricMap.metrics); n != 0 {
|
||||||
|
t.Error("expected no metrics, got", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run("zero labels", func(t *testing.T) {
|
||||||
|
c1 := vec.MustCurryWith(nil)
|
||||||
|
c2 := vec.MustCurryWith(nil)
|
||||||
|
c1.WithLabelValues("1", "2", "3").Inc()
|
||||||
|
c2.With(Labels{"one": "11", "two": "22", "three": "33"}).Inc()
|
||||||
|
assertMetrics(t)
|
||||||
|
if !c1.Delete(Labels{"one": "1", "two": "2", "three": "3"}) {
|
||||||
|
t.Error("deletion failed")
|
||||||
|
}
|
||||||
|
if !c2.DeleteLabelValues("11", "22", "33") {
|
||||||
|
t.Error("deletion failed")
|
||||||
|
}
|
||||||
|
assertNoMetric(t)
|
||||||
|
})
|
||||||
|
t.Run("first label", func(t *testing.T) {
|
||||||
|
c1 := vec.MustCurryWith(Labels{"one": "1"})
|
||||||
|
c2 := vec.MustCurryWith(Labels{"one": "11"})
|
||||||
|
c1.WithLabelValues("2", "3").Inc()
|
||||||
|
c2.With(Labels{"two": "22", "three": "33"}).Inc()
|
||||||
|
assertMetrics(t)
|
||||||
|
if c1.Delete(Labels{"two": "22", "three": "33"}) {
|
||||||
|
t.Error("deletion unexpectedly succeeded")
|
||||||
|
}
|
||||||
|
if c2.DeleteLabelValues("2", "3") {
|
||||||
|
t.Error("deletion unexpectedly succeeded")
|
||||||
|
}
|
||||||
|
if !c1.Delete(Labels{"two": "2", "three": "3"}) {
|
||||||
|
t.Error("deletion failed")
|
||||||
|
}
|
||||||
|
if !c2.DeleteLabelValues("22", "33") {
|
||||||
|
t.Error("deletion failed")
|
||||||
|
}
|
||||||
|
assertNoMetric(t)
|
||||||
|
})
|
||||||
|
t.Run("middle label", func(t *testing.T) {
|
||||||
|
c1 := vec.MustCurryWith(Labels{"two": "2"})
|
||||||
|
c2 := vec.MustCurryWith(Labels{"two": "22"})
|
||||||
|
c1.WithLabelValues("1", "3").Inc()
|
||||||
|
c2.With(Labels{"one": "11", "three": "33"}).Inc()
|
||||||
|
assertMetrics(t)
|
||||||
|
if c1.Delete(Labels{"one": "11", "three": "33"}) {
|
||||||
|
t.Error("deletion unexpectedly succeeded")
|
||||||
|
}
|
||||||
|
if c2.DeleteLabelValues("1", "3") {
|
||||||
|
t.Error("deletion unexpectedly succeeded")
|
||||||
|
}
|
||||||
|
if !c1.Delete(Labels{"one": "1", "three": "3"}) {
|
||||||
|
t.Error("deletion failed")
|
||||||
|
}
|
||||||
|
if !c2.DeleteLabelValues("11", "33") {
|
||||||
|
t.Error("deletion failed")
|
||||||
|
}
|
||||||
|
assertNoMetric(t)
|
||||||
|
})
|
||||||
|
t.Run("last label", func(t *testing.T) {
|
||||||
|
c1 := vec.MustCurryWith(Labels{"three": "3"})
|
||||||
|
c2 := vec.MustCurryWith(Labels{"three": "33"})
|
||||||
|
c1.WithLabelValues("1", "2").Inc()
|
||||||
|
c2.With(Labels{"one": "11", "two": "22"}).Inc()
|
||||||
|
assertMetrics(t)
|
||||||
|
if c1.Delete(Labels{"two": "22", "one": "11"}) {
|
||||||
|
t.Error("deletion unexpectedly succeeded")
|
||||||
|
}
|
||||||
|
if c2.DeleteLabelValues("1", "2") {
|
||||||
|
t.Error("deletion unexpectedly succeeded")
|
||||||
|
}
|
||||||
|
if !c1.Delete(Labels{"two": "2", "one": "1"}) {
|
||||||
|
t.Error("deletion failed")
|
||||||
|
}
|
||||||
|
if !c2.DeleteLabelValues("11", "22") {
|
||||||
|
t.Error("deletion failed")
|
||||||
|
}
|
||||||
|
assertNoMetric(t)
|
||||||
|
})
|
||||||
|
t.Run("two labels", func(t *testing.T) {
|
||||||
|
c1 := vec.MustCurryWith(Labels{"three": "3", "one": "1"})
|
||||||
|
c2 := vec.MustCurryWith(Labels{"three": "33", "one": "11"})
|
||||||
|
c1.WithLabelValues("2").Inc()
|
||||||
|
c2.With(Labels{"two": "22"}).Inc()
|
||||||
|
assertMetrics(t)
|
||||||
|
if c1.Delete(Labels{"two": "22"}) {
|
||||||
|
t.Error("deletion unexpectedly succeeded")
|
||||||
|
}
|
||||||
|
if c2.DeleteLabelValues("2") {
|
||||||
|
t.Error("deletion unexpectedly succeeded")
|
||||||
|
}
|
||||||
|
if !c1.Delete(Labels{"two": "2"}) {
|
||||||
|
t.Error("deletion failed")
|
||||||
|
}
|
||||||
|
if !c2.DeleteLabelValues("22") {
|
||||||
|
t.Error("deletion failed")
|
||||||
|
}
|
||||||
|
assertNoMetric(t)
|
||||||
|
})
|
||||||
|
t.Run("all labels", func(t *testing.T) {
|
||||||
|
c1 := vec.MustCurryWith(Labels{"three": "3", "two": "2", "one": "1"})
|
||||||
|
c2 := vec.MustCurryWith(Labels{"three": "33", "one": "11", "two": "22"})
|
||||||
|
c1.WithLabelValues().Inc()
|
||||||
|
c2.With(nil).Inc()
|
||||||
|
assertMetrics(t)
|
||||||
|
if !c1.Delete(Labels{}) {
|
||||||
|
t.Error("deletion failed")
|
||||||
|
}
|
||||||
|
if !c2.DeleteLabelValues() {
|
||||||
|
t.Error("deletion failed")
|
||||||
|
}
|
||||||
|
assertNoMetric(t)
|
||||||
|
})
|
||||||
|
t.Run("double curry", func(t *testing.T) {
|
||||||
|
c1 := vec.MustCurryWith(Labels{"three": "3"}).MustCurryWith(Labels{"one": "1"})
|
||||||
|
c2 := vec.MustCurryWith(Labels{"three": "33"}).MustCurryWith(Labels{"one": "11"})
|
||||||
|
c1.WithLabelValues("2").Inc()
|
||||||
|
c2.With(Labels{"two": "22"}).Inc()
|
||||||
|
assertMetrics(t)
|
||||||
|
if c1.Delete(Labels{"two": "22"}) {
|
||||||
|
t.Error("deletion unexpectedly succeeded")
|
||||||
|
}
|
||||||
|
if c2.DeleteLabelValues("2") {
|
||||||
|
t.Error("deletion unexpectedly succeeded")
|
||||||
|
}
|
||||||
|
if !c1.Delete(Labels{"two": "2"}) {
|
||||||
|
t.Error("deletion failed")
|
||||||
|
}
|
||||||
|
if !c2.DeleteLabelValues("22") {
|
||||||
|
t.Error("deletion failed")
|
||||||
|
}
|
||||||
|
assertNoMetric(t)
|
||||||
|
})
|
||||||
|
t.Run("use already curried label", func(t *testing.T) {
|
||||||
|
c1 := vec.MustCurryWith(Labels{"three": "3"})
|
||||||
|
if _, err := c1.GetMetricWithLabelValues("1", "2", "3"); err == nil {
|
||||||
|
t.Error("expected error when using already curried label")
|
||||||
|
}
|
||||||
|
if _, err := c1.GetMetricWith(Labels{"one": "1", "two": "2", "three": "3"}); err == nil {
|
||||||
|
t.Error("expected error when using already curried label")
|
||||||
|
}
|
||||||
|
assertNoMetric(t)
|
||||||
|
c1.WithLabelValues("1", "2").Inc()
|
||||||
|
if c1.Delete(Labels{"one": "1", "two": "2", "three": "3"}) {
|
||||||
|
t.Error("deletion unexpectedly succeeded")
|
||||||
|
}
|
||||||
|
if !c1.Delete(Labels{"one": "1", "two": "2"}) {
|
||||||
|
t.Error("deletion failed")
|
||||||
|
}
|
||||||
|
assertNoMetric(t)
|
||||||
|
})
|
||||||
|
t.Run("curry already curried label", func(t *testing.T) {
|
||||||
|
if _, err := vec.MustCurryWith(Labels{"three": "3"}).CurryWith(Labels{"three": "33"}); err == nil {
|
||||||
|
t.Error("currying unexpectedly succeeded")
|
||||||
|
} else if err.Error() != `label name "three" is already curried` {
|
||||||
|
t.Error("currying returned unexpected error:", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
})
|
||||||
|
t.Run("unknown label", func(t *testing.T) {
|
||||||
|
if _, err := vec.CurryWith(Labels{"foo": "bar"}); err == nil {
|
||||||
|
t.Error("currying unexpectedly succeeded")
|
||||||
|
} else if err.Error() != "1 unknown label(s) found during currying" {
|
||||||
|
t.Error("currying returned unexpected error:", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func BenchmarkMetricVecWithLabelValuesBasic(b *testing.B) {
|
func BenchmarkMetricVecWithLabelValuesBasic(b *testing.B) {
|
||||||
benchmarkMetricVecWithLabelValues(b, map[string][]string{
|
benchmarkMetricVecWithLabelValues(b, map[string][]string{
|
||||||
"l1": {"onevalue"},
|
"l1": {"onevalue"},
|
||||||
|
|
Loading…
Reference in New Issue