Create a public registry interface and separate out HTTP exposition
General context and approch
===========================
This is the first part of the long awaited wider refurbishment of
`client_golang/prometheus/...`. After a lot of struggling, I decided
to not go for one breaking big-bang, but cut things into smaller steps
after all, mostly to keep the changes manageable and easy to
review. I'm aiming for having the invasive breaking changes
concentrated in as few steps as possible (ideally one). Some steps
will not be breaking at all, but typically there will be breaking
changes that only affect quite special cases so that 95+% of users
will not be affected. This first step is an example for that, see
details below.
What's happening in this commit?
================================
This step is about finally creating an exported registry
interface. This could not be done by simply export the existing
internal implementation because the interface would be _way_ too
fat. This commit introduces a qutie lean `Registry` interface
(compared to the previous interval implementation). The functions that
act on the default registry are retained (with very few exceptions) so
that most use cases won't see a change. However, several of those are
deprecated now to clean up the namespace in the future.
The default registry is kept in the public variable
`DefaultRegistry`. This follows the example of the http package in the
standard library (cf. `http.DefaultServeMux`, `http.DefaultClient`)
with the same implications. (This pattern is somewhat disputed within
the Go community but I chose to go with the devil you know instead of
creating something more complex or even disallowing any changes to the
default registry. The current approach gives everybody the freedom to
not touch DefaultRegistry or to do everything with a custom registry
to play save.)
Another important part in making the registry lean is the extraction
of the HTTP exposition, which also allows for customization of the
HTTP exposition. Note that the separation of metric collection and
exposition has the side effect that managing the MetricFamily and
Metric protobuf objects in a free-list or pool isn't really feasible
anymore. By now (with better GC in more recent Go versions), the
returns were anyway dimisishing. To be effective at all, scrapes had
to happen more often than GC cycles, and even then most elements of
the protobufs (everything excetp the MetricFamily and Metric structs
themselves) would still cause allocation churn. In a future breaking
change, the signature of the Write method in the Metric interface will
be adjusted accordingly. In this commit, avoiding breakage is more
important.
The following issues are fixed by this commit (some solved "on the
fly" now that I was touching the code anyway and it would have been
stupid to port the bugs):
https://github.com/prometheus/client_golang/issues/46
https://github.com/prometheus/client_golang/issues/100
https://github.com/prometheus/client_golang/issues/170
https://github.com/prometheus/client_golang/issues/205
Documentation including examples have been amended as required.
What future changes does this commit enable?
============================================
The following items are not yet implemented, but this commit opens the
possibility of implementing these independently.
- The separation of the HTTP exposition allows the implementation of
other exposition methods based on the Registry interface, as known
from other Prometheus client libraries, e.g. sending the metrics to
Graphite.
Cf. https://github.com/prometheus/client_golang/issues/197
- The public `Registry` interface allows the implementation of
convenience tools for testing metrics collection. Those tools can
inspect the collected MetricFamily protobufs and compare them to
expectation. Also, tests can use their own testing instance of a
registry.
Cf. https://github.com/prometheus/client_golang/issues/58
Notable non-goals of this commit
================================
Non-goals that will be tackled later
------------------------------------
The following two issues are quite closely connected to the changes in
this commit but the line has been drawn deliberately to address them
in later steps of the refurbishment:
- `InstrumentHandler` has many known problems. The plan is to create a
saner way to conveniently intrument HTTP handlers and remove the old
`InstrumentHandler` altogether. To keep breakage low for now, even
the default handler to expose metrics is still using the old
`InstrumentHandler`. This leads to weird naming inconsistencies but
I have deemed it better to not break the world right now but do it
in the change that provides better ways of instrumenting HTTP
handlers.
Cf. https://github.com/prometheus/client_golang/issues/200
- There is work underway to make the whole handling of metric
descriptors (`Desc`) more intuitive and transparent for the user
(including an ability for less strict checking,
cf. https://github.com/prometheus/client_golang/issues/47). That's
quite invasive from the perspective of the internal code, namely the
registry. I deliberately kept those changes out of this commit.
- While this commit adds new external dependency, the effort to vendor
anything within the library that is not visible in any exported
types will have to be done later.
Non-goals that _might_ be tackled later
---------------------------------------
There is a strong and understandable urge to divide the `prometheus`
package into a number of sub-packages (like `registry`, `collectors`,
`http`, `metrics`, …). However, to not run into a multitude of
circular import chains, this would need to break every single existing
usage of the library. (As just one example, if the ubiquitious
`prometheus.MustRegister` (with more than 2,000 uses on GitHub alone)
is kept in the `prometheus` package, but the other registry concerns
go into a new `registry` package, then the `prometheus` package would
import the `registry` package (to call the actual register method),
while at the same time the `registry` package needs to import the
`prometheus` package to access `Collector`, `Metric`, `Desc` and
more. If we moved `MustRegister` into the `registry` package,
thousands of code lines would have to be fixed (which would be easy if
the world was a mono repo, but it is not). If we moved everything else
the proposed registry package needs into packages of their own, we
would break thousands of other code lines.)
The main problem is really the top-level functions like
`MustRegister`, `Handler`, …, which effectively pull everything into
one package. Those functions are however very convenient for the easy
and very frequent use-cases.
This problem has to be revisited later.
For now, I'm trying to keep the amount of exported names in the
package as low as possible (e.g. I unexported expvarCollector in this
commit because the NewExpvarCollector constructor is enough to export,
and it is now consistent with other collectors, like the goCollector).
Non-goals that won't be tackled anytime soon
--------------------------------------------
Something that I have played with a lot is "streaming collection",
i.e. allow an implementation of the `Registry` interface that collects
metrics incrementally and serves them while doing so. As it has turned
out, this has many many issues and makes the `Registry` interface very
clunky. Eventually, I made the call that it is unlikely we will really
implement streaming collection; and making the interface more clunky
for something that might not even happen is really a big no-no. Note
that the `Registry` interface only creates the in-memory
representation of the metric family protobufs in one go. The
serializaton onto the wire can still be handled in a streaming fashion
(which hasn't been done so far, without causing any trouble, but might
be done in the future without breaking any interfaces).
What are the breaking changes?
==============================
- Signatures of functions pushing to Pushgateway have changed to allow
arbitrary grouping (which was planned for a long time anyway, and
now that I had to work on the Push code anyway for the registry
refurbishment, I finally did it,
cf. https://github.com/prometheus/client_golang/issues/100).
With the gained insight that pushing to the default registry is almost
never the right thing, and now that we are breaking the Push call
anyway, all the Push functions were moved to their own package,
which cleans up the namespace and is more idiomatic (pushing
Collectors is now literally done by `push.Collectors(...)`).
- The registry is doing more consistency checks by default now. Past
creators of inconsistent metrics could have masked the problem by
not setting `EnableCollectChecks`. Those inconsistencies will now be
detected. (But note that a "best effort" metrics collection is now
possible with `HandlerOpts.ErrorHandling = ContinueOnError`.)
- `EnableCollectChecks` is gone. The registry is now performing some
of those checks anyway (see previous item), and a registry with all
of those checks can now be created with `NewPedanticRegistry` (only
used for testing).
- `PanicOnCollectError` is gone. This behavior can now be configured
when creating a custom HTTP handler.
2016-07-20 18:11:14 +03:00
|
|
|
// Copyright 2016 The Prometheus Authors
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
//
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
//
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
// limitations under the License.
|
|
|
|
|
2014-05-07 22:08:33 +04:00
|
|
|
package prometheus
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"sort"
|
|
|
|
"strings"
|
|
|
|
|
2015-06-01 16:41:09 +03:00
|
|
|
"github.com/golang/protobuf/proto"
|
2016-11-11 18:59:23 +03:00
|
|
|
"github.com/prometheus/common/model"
|
2014-05-07 22:08:33 +04:00
|
|
|
|
2015-02-27 18:12:59 +03:00
|
|
|
dto "github.com/prometheus/client_model/go"
|
2014-05-07 22:08:33 +04:00
|
|
|
)
|
|
|
|
|
2015-08-23 14:51:32 +03:00
|
|
|
// reservedLabelPrefix is a prefix which is not legal in user-supplied
|
|
|
|
// label names.
|
|
|
|
const reservedLabelPrefix = "__"
|
|
|
|
|
2014-05-07 22:08:33 +04:00
|
|
|
// Labels represents a collection of label name -> value mappings. This type is
|
|
|
|
// commonly used with the With(Labels) and GetMetricWith(Labels) methods of
|
|
|
|
// metric vector Collectors, e.g.:
|
|
|
|
// myVec.With(Labels{"code": "404", "method": "GET"}).Add(42)
|
|
|
|
//
|
|
|
|
// The other use-case is the specification of constant label pairs in Opts or to
|
|
|
|
// create a Desc.
|
|
|
|
type Labels map[string]string
|
|
|
|
|
|
|
|
// Desc is the descriptor used by every Prometheus Metric. It is essentially
|
|
|
|
// the immutable meta-data of a Metric. The normal Metric implementations
|
|
|
|
// included in this package manage their Desc under the hood. Users only have to
|
|
|
|
// deal with Desc if they use advanced features like the ExpvarCollector or
|
|
|
|
// custom Collectors and Metrics.
|
|
|
|
//
|
|
|
|
// Descriptors registered with the same registry have to fulfill certain
|
|
|
|
// consistency and uniqueness criteria if they share the same fully-qualified
|
|
|
|
// name: They must have the same help string and the same label names (aka label
|
|
|
|
// dimensions) in each, constLabels and variableLabels, but they must differ in
|
|
|
|
// the values of the constLabels.
|
|
|
|
//
|
|
|
|
// Descriptors that share the same fully-qualified names and the same label
|
|
|
|
// values of their constLabels are considered equal.
|
|
|
|
//
|
|
|
|
// Use NewDesc to create new Desc instances.
|
|
|
|
type Desc struct {
|
|
|
|
// fqName has been built from Namespace, Subsystem, and Name.
|
|
|
|
fqName string
|
|
|
|
// help provides some helpful information about this metric.
|
|
|
|
help string
|
|
|
|
// constLabelPairs contains precalculated DTO label pairs based on
|
|
|
|
// the constant labels.
|
|
|
|
constLabelPairs []*dto.LabelPair
|
|
|
|
// VariableLabels contains names of labels for which the metric
|
|
|
|
// maintains variable values.
|
|
|
|
variableLabels []string
|
|
|
|
// id is a hash of the values of the ConstLabels and fqName. This
|
|
|
|
// must be unique among all registered descriptors and can therefore be
|
|
|
|
// used as an identifier of the descriptor.
|
|
|
|
id uint64
|
|
|
|
// dimHash is a hash of the label names (preset and variable) and the
|
|
|
|
// Help string. Each Desc with the same fqName must have the same
|
|
|
|
// dimHash.
|
|
|
|
dimHash uint64
|
2016-09-16 20:59:04 +03:00
|
|
|
// err is an error that occurred during construction. It is reported on
|
2014-05-07 22:08:33 +04:00
|
|
|
// registration time.
|
|
|
|
err error
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewDesc allocates and initializes a new Desc. Errors are recorded in the Desc
|
|
|
|
// and will be reported on registration time. variableLabels and constLabels can
|
|
|
|
// be nil if no such labels should be set. fqName and help must not be empty.
|
|
|
|
//
|
|
|
|
// variableLabels only contain the label names. Their label values are variable
|
|
|
|
// and therefore not part of the Desc. (They are managed within the Metric.)
|
|
|
|
//
|
|
|
|
// For constLabels, the label values are constant. Therefore, they are fully
|
|
|
|
// specified in the Desc. See the Opts documentation for the implications of
|
|
|
|
// constant labels.
|
|
|
|
func NewDesc(fqName, help string, variableLabels []string, constLabels Labels) *Desc {
|
|
|
|
d := &Desc{
|
|
|
|
fqName: fqName,
|
|
|
|
help: help,
|
|
|
|
variableLabels: variableLabels,
|
|
|
|
}
|
|
|
|
if help == "" {
|
|
|
|
d.err = errors.New("empty help string")
|
|
|
|
return d
|
|
|
|
}
|
2016-11-11 18:59:23 +03:00
|
|
|
if !model.IsValidMetricName(model.LabelValue(fqName)) {
|
2014-05-07 22:08:33 +04:00
|
|
|
d.err = fmt.Errorf("%q is not a valid metric name", fqName)
|
|
|
|
return d
|
|
|
|
}
|
|
|
|
// labelValues contains the label values of const labels (in order of
|
|
|
|
// their sorted label names) plus the fqName (at position 0).
|
|
|
|
labelValues := make([]string, 1, len(constLabels)+1)
|
|
|
|
labelValues[0] = fqName
|
|
|
|
labelNames := make([]string, 0, len(constLabels)+len(variableLabels))
|
|
|
|
labelNameSet := map[string]struct{}{}
|
|
|
|
// First add only the const label names and sort them...
|
|
|
|
for labelName := range constLabels {
|
|
|
|
if !checkLabelName(labelName) {
|
|
|
|
d.err = fmt.Errorf("%q is not a valid label name", labelName)
|
|
|
|
return d
|
|
|
|
}
|
|
|
|
labelNames = append(labelNames, labelName)
|
|
|
|
labelNameSet[labelName] = struct{}{}
|
|
|
|
}
|
|
|
|
sort.Strings(labelNames)
|
|
|
|
// ... so that we can now add const label values in the order of their names.
|
|
|
|
for _, labelName := range labelNames {
|
|
|
|
labelValues = append(labelValues, constLabels[labelName])
|
|
|
|
}
|
2017-08-20 00:31:56 +03:00
|
|
|
// Validate the const label values. They can't have a wrong cardinality, so
|
|
|
|
// use in len(labelValues) as expectedNumberOfValues.
|
|
|
|
if err := validateLabelValues(labelValues, len(labelValues)); err != nil {
|
|
|
|
d.err = err
|
|
|
|
return d
|
|
|
|
}
|
2014-05-07 22:08:33 +04:00
|
|
|
// Now add the variable label names, but prefix them with something that
|
|
|
|
// cannot be in a regular label name. That prevents matching the label
|
|
|
|
// dimension with a different mix between preset and variable labels.
|
|
|
|
for _, labelName := range variableLabels {
|
|
|
|
if !checkLabelName(labelName) {
|
|
|
|
d.err = fmt.Errorf("%q is not a valid label name", labelName)
|
|
|
|
return d
|
|
|
|
}
|
|
|
|
labelNames = append(labelNames, "$"+labelName)
|
|
|
|
labelNameSet[labelName] = struct{}{}
|
|
|
|
}
|
|
|
|
if len(labelNames) != len(labelNameSet) {
|
|
|
|
d.err = errors.New("duplicate label names")
|
|
|
|
return d
|
|
|
|
}
|
2017-08-20 00:31:56 +03:00
|
|
|
|
2015-11-12 15:55:12 +03:00
|
|
|
vh := hashNew()
|
2014-05-07 22:08:33 +04:00
|
|
|
for _, val := range labelValues {
|
2015-11-12 15:55:12 +03:00
|
|
|
vh = hashAdd(vh, val)
|
|
|
|
vh = hashAddByte(vh, separatorByte)
|
2014-05-07 22:08:33 +04:00
|
|
|
}
|
2015-11-12 15:55:12 +03:00
|
|
|
d.id = vh
|
2014-05-07 22:08:33 +04:00
|
|
|
// Sort labelNames so that order doesn't matter for the hash.
|
|
|
|
sort.Strings(labelNames)
|
|
|
|
// Now hash together (in this order) the help string and the sorted
|
|
|
|
// label names.
|
2015-11-12 15:55:12 +03:00
|
|
|
lh := hashNew()
|
|
|
|
lh = hashAdd(lh, help)
|
|
|
|
lh = hashAddByte(lh, separatorByte)
|
2014-05-07 22:08:33 +04:00
|
|
|
for _, labelName := range labelNames {
|
2015-11-12 15:55:12 +03:00
|
|
|
lh = hashAdd(lh, labelName)
|
|
|
|
lh = hashAddByte(lh, separatorByte)
|
2014-05-07 22:08:33 +04:00
|
|
|
}
|
2015-11-12 15:55:12 +03:00
|
|
|
d.dimHash = lh
|
2014-05-07 22:08:33 +04:00
|
|
|
|
|
|
|
d.constLabelPairs = make([]*dto.LabelPair, 0, len(constLabels))
|
|
|
|
for n, v := range constLabels {
|
|
|
|
d.constLabelPairs = append(d.constLabelPairs, &dto.LabelPair{
|
|
|
|
Name: proto.String(n),
|
|
|
|
Value: proto.String(v),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
sort.Sort(LabelPairSorter(d.constLabelPairs))
|
|
|
|
return d
|
|
|
|
}
|
|
|
|
|
Allow error reporting during metrics collection and simplify Register().
Both are interface changes I want to get in before public
announcement. They only break rare usage cases, and are always easy to
fix, but still we want to avoid breaking changes after a wider
announcement of the project.
The change of Register() simply removes the return of the Collector,
which nobody was using in practice. It was just bloating the call
syntax. Note that this is different from RegisterOrGet(), which is
used at various occasions where you want to register something that
might or might not be registered already, but if it is, you want the
previously registered Collector back (because that's the relevant
one).
WRT error reporting: I first tried the obvious way of letting the
Collector methods Describe() and Collect() return error. However, I
had to conclude that that bloated _many_ calls and their handling in
very obnoxious ways. On the other hand, the case where you actually
want to report errors during registration or collection is very
rare. Hence, this approach has the wrong trade-off. The approach taken
here might at first appear clunky but is in practice quite handy,
mostly because there is almost no change for the "normal" case of "no
special error handling", but also because it plays well with the way
descriptors and metrics are handled (via channels).
Explaining the approach in more detail:
- During registration / describe: Error handling was actually already
in place (for invalid descriptors, which carry an error anyway). I
only added a convenience function to create an invalid descriptor
with a given error on purpose.
- Metrics are now treated in a similar way. The Write method returns
an error now (the only change in interface). An "invalid metric" is
provided that can be sent via the channel to signal that that metric
could not be collected. It alse transports an error.
NON-GOALS OF THIS COMMIT:
This is NOT yet the major improvement of the whole registry part,
where we want a public Registry interface and plenty of modular
configurations (for error handling, various auto-metrics, http
instrumentation, testing, ...). However, we can do that whole thing
without breaking existing interfaces. For now (which is a significant
issue) any error during collection will either cause a 500 HTTP
response or a panic (depending on registry config). Later, we
definitely want to have a possibility to skip (and only report
somehow) non-collectible metrics instead of aborting the whole scrape.
2015-01-12 21:16:09 +03:00
|
|
|
// NewInvalidDesc returns an invalid descriptor, i.e. a descriptor with the
|
|
|
|
// provided error set. If a collector returning such a descriptor is registered,
|
|
|
|
// registration will fail with the provided error. NewInvalidDesc can be used by
|
|
|
|
// a Collector to signal inability to describe itself.
|
|
|
|
func NewInvalidDesc(err error) *Desc {
|
|
|
|
return &Desc{
|
|
|
|
err: err,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-05-07 22:08:33 +04:00
|
|
|
func (d *Desc) String() string {
|
|
|
|
lpStrings := make([]string, 0, len(d.constLabelPairs))
|
|
|
|
for _, lp := range d.constLabelPairs {
|
|
|
|
lpStrings = append(
|
|
|
|
lpStrings,
|
2014-06-20 22:40:48 +04:00
|
|
|
fmt.Sprintf("%s=%q", lp.GetName(), lp.GetValue()),
|
2014-05-07 22:08:33 +04:00
|
|
|
)
|
|
|
|
}
|
|
|
|
return fmt.Sprintf(
|
|
|
|
"Desc{fqName: %q, help: %q, constLabels: {%s}, variableLabels: %v}",
|
|
|
|
d.fqName,
|
|
|
|
d.help,
|
|
|
|
strings.Join(lpStrings, ","),
|
|
|
|
d.variableLabels,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
func checkLabelName(l string) bool {
|
2016-11-11 18:59:23 +03:00
|
|
|
return model.LabelName(l).IsValid() &&
|
2015-08-23 14:51:32 +03:00
|
|
|
!strings.HasPrefix(l, reservedLabelPrefix)
|
2014-05-07 22:08:33 +04:00
|
|
|
}
|