Add HandlerWithAllowlist which can control exposed metrics

This commit is contained in:
Catherine Fang 2023-08-12 17:10:50 -04:00
parent 1a88780343
commit bf4494e8fd
1 changed files with 31 additions and 0 deletions

View File

@ -37,6 +37,7 @@ import (
"fmt"
"io"
"net/http"
"regexp"
"strconv"
"strings"
"sync"
@ -45,6 +46,8 @@ import (
"github.com/prometheus/common/expfmt"
"github.com/prometheus/client_golang/prometheus"
dto "github.com/prometheus/client_model/go"
)
const (
@ -90,6 +93,13 @@ func HandlerFor(reg prometheus.Gatherer, opts HandlerOpts) http.Handler {
return HandlerForTransactional(prometheus.ToTransactionalGatherer(reg), opts)
}
// HandlerWithAllowlist remove metrics whose name can't match with metricNameMatcher
func HandlerWithAllowlist(metricNameMatcher *regexp.Regexp) http.Handler {
return InstrumentMetricHandler(
prometheus.DefaultRegisterer, HandlerFor(&FilteredGatherer{gather: prometheus.DefaultGatherer, metricNameMatcher: metricNameMatcher}, HandlerOpts{}),
)
}
// HandlerForTransactional is like HandlerFor, but it uses transactional gather, which
// can safely change in-place returned *dto.MetricFamily before call to `Gather` and after
// call to `done` of that `Gather`.
@ -406,3 +416,24 @@ func httpError(rsp http.ResponseWriter, err error) {
http.StatusInternalServerError,
)
}
type FilteredGatherer struct {
gather prometheus.Gatherer
metricNameMatcher *regexp.Regexp
}
func (f *FilteredGatherer) Gather() ([]*dto.MetricFamily, error) {
results := []*dto.MetricFamily{}
metrics, err := f.gather.Gather()
if err != nil {
return nil, err
}
for _, m := range metrics {
if f.metricNameMatcher.MatchString(*m.Name) {
results = append(results, m)
}
}
return results, nil
}