@@ -37,6 +37,7 @@ import (
37
37
"fmt"
38
38
"io"
39
39
"net/http"
40
+ "regexp"
40
41
"strconv"
41
42
"strings"
42
43
"sync"
@@ -45,6 +46,8 @@ import (
45
46
"github.com/prometheus/common/expfmt"
46
47
47
48
"github.com/prometheus/client_golang/prometheus"
49
+
50
+ dto "github.com/prometheus/client_model/go"
48
51
)
49
52
50
53
const (
@@ -90,6 +93,13 @@ func HandlerFor(reg prometheus.Gatherer, opts HandlerOpts) http.Handler {
90
93
return HandlerForTransactional (prometheus .ToTransactionalGatherer (reg ), opts )
91
94
}
92
95
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
+
93
103
// HandlerForTransactional is like HandlerFor, but it uses transactional gather, which
94
104
// can safely change in-place returned *dto.MetricFamily before call to `Gather` and after
95
105
// call to `done` of that `Gather`.
@@ -406,3 +416,32 @@ func httpError(rsp http.ResponseWriter, err error) {
406
416
http .StatusInternalServerError ,
407
417
)
408
418
}
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