Skip to content

Commit 19e5daa

Browse files
Add HandlerWithAllowlist which can control exposed metrics
1 parent 1a88780 commit 19e5daa

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

prometheus/promhttp/http.go

+39
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ import (
3737
"fmt"
3838
"io"
3939
"net/http"
40+
"regexp"
4041
"strconv"
4142
"strings"
4243
"sync"
@@ -45,6 +46,8 @@ import (
4546
"github.com/prometheus/common/expfmt"
4647

4748
"github.com/prometheus/client_golang/prometheus"
49+
50+
dto "github.com/prometheus/client_model/go"
4851
)
4952

5053
const (
@@ -90,6 +93,13 @@ func HandlerFor(reg prometheus.Gatherer, opts HandlerOpts) http.Handler {
9093
return HandlerForTransactional(prometheus.ToTransactionalGatherer(reg), opts)
9194
}
9295

96+
// HandlerWithAllowlist remove metrics whose name can't match with metricNameMatcher
97+
func HandlerWithAllowlist(metricNameMatcher *regexp.Regexp) http.Handler {
98+
return InstrumentMetricHandler(
99+
prometheus.DefaultRegisterer, HandlerFor(&FilteredGatherer{gather: prometheus.DefaultGatherer, metricNameMatcher: metricNameMatcher}, HandlerOpts{}),
100+
)
101+
}
102+
93103
// HandlerForTransactional is like HandlerFor, but it uses transactional gather, which
94104
// can safely change in-place returned *dto.MetricFamily before call to `Gather` and after
95105
// call to `done` of that `Gather`.
@@ -406,3 +416,32 @@ func httpError(rsp http.ResponseWriter, err error) {
406416
http.StatusInternalServerError,
407417
)
408418
}
419+
420+
type FilteredGatherer struct {
421+
gather prometheus.Gatherer
422+
metricNameMatcher *regexp.Regexp
423+
}
424+
425+
// NewFilteredGatherer creates FilteredGatherer.
426+
func NewFilteredGatherer(gather prometheus.Gatherer, metricNameMatcher *regexp.Regexp) *FilteredGatherer {
427+
return &FilteredGatherer{
428+
gather: gather,
429+
metricNameMatcher: metricNameMatcher,
430+
}
431+
}
432+
433+
func (f *FilteredGatherer) Gather() ([]*dto.MetricFamily, error) {
434+
results := []*dto.MetricFamily{}
435+
metrics, err := f.gather.Gather()
436+
if err != nil {
437+
return nil, err
438+
}
439+
for _, m := range metrics {
440+
441+
if f.metricNameMatcher.MatchString(*m.Name) {
442+
results = append(results, m)
443+
}
444+
445+
}
446+
return results, nil
447+
}

0 commit comments

Comments
 (0)