Skip to content

Commit

Permalink
Add HandlerWithAllowlist which can control exposed metrics
Browse files Browse the repository at this point in the history
  • Loading branch information
CatherineF-dev committed Aug 14, 2023
1 parent 1a88780 commit 19e5daa
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions prometheus/promhttp/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import (
"fmt"
"io"
"net/http"
"regexp"
"strconv"
"strings"
"sync"
Expand All @@ -45,6 +46,8 @@ import (
"github.com/prometheus/common/expfmt"

"github.com/prometheus/client_golang/prometheus"

dto "github.com/prometheus/client_model/go"
)

const (
Expand Down Expand Up @@ -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`.
Expand Down Expand Up @@ -406,3 +416,32 @@ func httpError(rsp http.ResponseWriter, err error) {
http.StatusInternalServerError,
)
}

type FilteredGatherer struct {
gather prometheus.Gatherer

Check failure on line 421 in prometheus/promhttp/http.go

View workflow job for this annotation

GitHub Actions / lint

File is not `gofmt`-ed with `-s` (gofmt)
metricNameMatcher *regexp.Regexp
}

// NewFilteredGatherer creates FilteredGatherer.
func NewFilteredGatherer(gather prometheus.Gatherer, metricNameMatcher *regexp.Regexp) *FilteredGatherer {
return &FilteredGatherer{
gather: gather,
metricNameMatcher: metricNameMatcher,
}
}

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 {

Check failure on line 440 in prometheus/promhttp/http.go

View workflow job for this annotation

GitHub Actions / lint

File is not `gofumpt`-ed with `-extra` (gofumpt)
if f.metricNameMatcher.MatchString(*m.Name) {
results = append(results, m)
}

Check failure on line 444 in prometheus/promhttp/http.go

View workflow job for this annotation

GitHub Actions / lint

File is not `gofumpt`-ed with `-extra` (gofumpt)
}
return results, nil
}

0 comments on commit 19e5daa

Please sign in to comment.