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 12, 2023
1 parent 1a88780 commit 90037a6
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions prometheus/promhttp/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,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 +92,16 @@ func HandlerFor(reg prometheus.Gatherer, opts HandlerOpts) http.Handler {
return HandlerForTransactional(prometheus.ToTransactionalGatherer(reg), opts)
}

func HandlerWithAllowlist(metricNames []string) http.Handler {
allowedMetrics := map[string]bool{}
for _, m := range metricNames {
allowedMetrics[m] = true
}
return InstrumentMetricHandler(
prometheus.DefaultRegisterer, HandlerFor(&FilteredDefaultGatherer{allowedMetrics: allowedMetrics}, 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 @@ -381,6 +393,35 @@ type HandlerOpts struct {
ProcessStartTime time.Time
}

type FilteredDefaultGatherer struct {
allowedMetrics map[string]bool
}

func (f *FilteredDefaultGatherer) Gather() ([]*dto.MetricFamily, error) {
results := []*dto.MetricFamily{}
metrics, err := prometheus.DefaultGatherer.Gather()
if err != nil {
return nil, err
}
for _, m := range metrics {
name := *m.Name
keep := false

if strings.HasPrefix(name, "go_") || strings.HasPrefix(name, "process_") || strings.HasPrefix(name, "promhttp_") {
keep = true
}

if f.allowedMetrics[name] {
keep = true
}

if keep {
results = append(results, m)
}
}
return results, nil
}

// gzipAccepted returns whether the client will accept gzip-encoded content.
func gzipAccepted(header http.Header) bool {
a := header.Get(acceptEncodingHeader)
Expand Down

0 comments on commit 90037a6

Please sign in to comment.