-
Notifications
You must be signed in to change notification settings - Fork 1
goodhistogram: add Prometheus adapter layer #2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
765e86b
goodhistogram: add Prometheus adapter layer
angles-n-daemons 6941efb
Merge branch 'main' into bdillmann/prometheus-collector
angles-n-daemons 7e72115
goodhistogram: add windowed histogram with Prometheus integration
angles-n-daemons 796027d
Merge pull request #4 from cockroachdb/bdillmann/windowed-histogram
angles-n-daemons File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| // Copyright 2026 The Cockroach Authors. | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
|
|
||
| package goodhistogram | ||
|
|
||
| import ( | ||
| "github.com/prometheus/client_golang/prometheus" | ||
| prometheusgo "github.com/prometheus/client_model/go" | ||
| ) | ||
|
|
||
| // PrometheusCollector wraps a Histogram as a prometheus.Collector, allowing it | ||
| // to be registered with a Prometheus registry for scraping. Recording is done | ||
| // directly on the Histogram; the collector only participates in the export path. | ||
| type PrometheusCollector struct { | ||
| h *Histogram | ||
| desc *prometheus.Desc | ||
| } | ||
|
|
||
| // ToPrometheusCollector returns a PrometheusCollector that exposes this | ||
| // histogram to a Prometheus registry. The returned collector implements | ||
| // prometheus.Collector and can be passed to prometheus.MustRegister. | ||
| func (h *Histogram) ToPrometheusCollector(desc *prometheus.Desc) *PrometheusCollector { | ||
| return &PrometheusCollector{h: h, desc: desc} | ||
| } | ||
|
|
||
| // Describe implements prometheus.Collector. | ||
| func (p *PrometheusCollector) Describe(ch chan<- *prometheus.Desc) { | ||
| ch <- p.desc | ||
| } | ||
|
|
||
| // Collect implements prometheus.Collector. A fresh histogramMetric is | ||
| // created per scrape so the Collector and Metric roles are separate. | ||
| func (p *PrometheusCollector) Collect(ch chan<- prometheus.Metric) { | ||
| ch <- &histogramMetric{ | ||
| desc: p.desc, | ||
| h: p.h, | ||
| } | ||
| } | ||
|
|
||
| // ToPrometheusMetric returns a point-in-time snapshot as a | ||
| // prometheusgo.Metric. This bridges to CockroachDB's PrometheusExportable | ||
| // interface without going through the Collector/Metric channel path. | ||
| func (p *PrometheusCollector) ToPrometheusMetric() *prometheusgo.Metric { | ||
| snap := p.h.Snapshot() | ||
| return &prometheusgo.Metric{ | ||
| Histogram: snap.ToPrometheusHistogram(), | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| // Copyright 2026 The Cockroach Authors. | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
|
|
||
| package goodhistogram | ||
|
|
||
| import ( | ||
| "testing" | ||
|
|
||
| "github.com/prometheus/client_golang/prometheus" | ||
| prometheusgo "github.com/prometheus/client_model/go" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func TestPrometheusCollectorRegistration(t *testing.T) { | ||
| h := New(Params{Lo: 100, Hi: 1e9}) | ||
| desc := prometheus.NewDesc("test_hist", "test", nil, nil) | ||
| collector := h.ToPrometheusCollector(desc) | ||
|
|
||
| reg := prometheus.NewRegistry() | ||
| require.NoError(t, reg.Register(collector)) | ||
|
|
||
| h.Record(500) | ||
| h.Record(1000) | ||
| h.Record(2000) | ||
|
|
||
| families, err := reg.Gather() | ||
| require.NoError(t, err) | ||
| require.Len(t, families, 1) | ||
| require.Equal(t, "test_hist", *families[0].Name) | ||
|
|
||
| metrics := families[0].Metric | ||
| require.Len(t, metrics, 1) | ||
| require.Equal(t, uint64(3), *metrics[0].Histogram.SampleCount) | ||
| require.Equal(t, float64(3500), *metrics[0].Histogram.SampleSum) | ||
| } | ||
|
|
||
| func TestPrometheusCollectorMatchesSnapshot(t *testing.T) { | ||
| h := New(Params{Lo: 100, Hi: 1e9}) | ||
| for _, v := range []int64{150, 999, 5000, 100000, 5000000} { | ||
| h.Record(v) | ||
| } | ||
|
|
||
| // Collect via the PrometheusCollector and extract the metric. | ||
| desc := prometheus.NewDesc("test_hist", "test", nil, nil) | ||
| collector := h.ToPrometheusCollector(desc) | ||
| ch := make(chan prometheus.Metric, 1) | ||
| collector.Collect(ch) | ||
| metric := <-ch | ||
| var collected prometheusgo.Metric | ||
| require.NoError(t, metric.Write(&collected)) | ||
|
|
||
| // Export directly via Snapshot. | ||
| snap := h.Snapshot() | ||
| direct := snap.ToPrometheusHistogram() | ||
|
|
||
| require.Equal(t, direct.GetSampleCount(), collected.Histogram.GetSampleCount()) | ||
| require.Equal(t, direct.GetSampleSum(), collected.Histogram.GetSampleSum()) | ||
| require.Equal(t, direct.GetSchema(), collected.Histogram.GetSchema()) | ||
| require.Equal(t, len(direct.GetBucket()), len(collected.Histogram.GetBucket())) | ||
| require.Equal(t, len(direct.GetPositiveSpan()), len(collected.Histogram.GetPositiveSpan())) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,151 @@ | ||
| // Copyright 2026 The Cockroach Authors. | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
|
|
||
| package goodhistogram | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "strings" | ||
| "sync" | ||
|
|
||
| "github.com/prometheus/client_golang/prometheus" | ||
| prometheusgo "github.com/prometheus/client_model/go" | ||
| ) | ||
|
|
||
| // HistogramVec is a collection of Histograms partitioned by label values. | ||
| // It implements prometheus.Collector so the entire vec can be registered | ||
| // with a Prometheus registry. Recording is done on the individual | ||
| // *Histogram returned by WithLabelValues. | ||
| type HistogramVec struct { | ||
| params Params | ||
| desc *prometheus.Desc | ||
| labelNames []string | ||
|
|
||
| mu struct { | ||
| sync.RWMutex | ||
| histograms map[string]*labeledHistogram | ||
| } | ||
| } | ||
|
|
||
| type labeledHistogram struct { | ||
| h *Histogram | ||
| labelPairs []*prometheusgo.LabelPair | ||
| } | ||
|
|
||
| // NewHistogramVec creates a new HistogramVec. All child histograms share the | ||
| // same Params. The desc is created internally from name, help, and labelNames. | ||
| func NewHistogramVec(p Params, name, help string, labelNames []string) *HistogramVec { | ||
| v := &HistogramVec{ | ||
| params: p, | ||
| desc: prometheus.NewDesc(name, help, labelNames, nil), | ||
| labelNames: labelNames, | ||
| } | ||
| v.mu.histograms = make(map[string]*labeledHistogram) | ||
| return v | ||
| } | ||
|
|
||
| // WithLabelValues returns the Histogram for the given label values, | ||
| // creating it if it doesn't exist. Panics if the number of values | ||
| // doesn't match the number of label names. | ||
| func (v *HistogramVec) WithLabelValues(lvs ...string) *Histogram { | ||
| if len(lvs) != len(v.labelNames) { | ||
| panic(fmt.Sprintf( | ||
| "goodhistogram: expected %d label values, got %d", | ||
| len(v.labelNames), len(lvs), | ||
| )) | ||
| } | ||
| key := strings.Join(lvs, "\xff") | ||
|
|
||
| v.mu.RLock() | ||
| if lh, ok := v.mu.histograms[key]; ok { | ||
| v.mu.RUnlock() | ||
| return lh.h | ||
| } | ||
| v.mu.RUnlock() | ||
|
|
||
| v.mu.Lock() | ||
| defer v.mu.Unlock() | ||
| if lh, ok := v.mu.histograms[key]; ok { | ||
| return lh.h | ||
| } | ||
| h := New(v.params) | ||
| v.mu.histograms[key] = &labeledHistogram{ | ||
| h: h, | ||
| labelPairs: makeLabelPairs(v.labelNames, lvs), | ||
| } | ||
| return h | ||
| } | ||
|
|
||
| // DeleteLabelValues removes the Histogram for the given label values. | ||
| // Returns true if the entry existed. Panics if the number of values | ||
| // doesn't match the number of label names. | ||
| func (v *HistogramVec) DeleteLabelValues(lvs ...string) bool { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do we need the same
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We do! adding it now |
||
| if len(lvs) != len(v.labelNames) { | ||
| panic(fmt.Sprintf( | ||
| "goodhistogram: expected %d label values, got %d", | ||
| len(v.labelNames), len(lvs), | ||
| )) | ||
| } | ||
| key := strings.Join(lvs, "\xff") | ||
| v.mu.Lock() | ||
| defer v.mu.Unlock() | ||
| _, ok := v.mu.histograms[key] | ||
| delete(v.mu.histograms, key) | ||
| return ok | ||
| } | ||
|
|
||
| // Reset removes all child histograms. | ||
| func (v *HistogramVec) Reset() { | ||
| v.mu.Lock() | ||
| defer v.mu.Unlock() | ||
| v.mu.histograms = make(map[string]*labeledHistogram) | ||
| } | ||
|
|
||
| // Describe implements prometheus.Collector. | ||
| func (v *HistogramVec) Describe(ch chan<- *prometheus.Desc) { | ||
| ch <- v.desc | ||
| } | ||
|
|
||
| // Collect implements prometheus.Collector. | ||
| func (v *HistogramVec) Collect(ch chan<- prometheus.Metric) { | ||
| v.mu.RLock() | ||
| defer v.mu.RUnlock() | ||
| for _, lh := range v.mu.histograms { | ||
| ch <- &histogramMetric{ | ||
| desc: v.desc, | ||
| h: lh.h, | ||
| labelPairs: lh.labelPairs, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // histogramMetric implements prometheus.Metric for a single labeled histogram. | ||
| type histogramMetric struct { | ||
| desc *prometheus.Desc | ||
| h *Histogram | ||
| labelPairs []*prometheusgo.LabelPair | ||
| } | ||
|
|
||
| func (m *histogramMetric) Desc() *prometheus.Desc { return m.desc } | ||
|
|
||
| func (m *histogramMetric) Write(out *prometheusgo.Metric) error { | ||
| snap := m.h.Snapshot() | ||
| out.Histogram = snap.ToPrometheusHistogram() | ||
| out.Label = m.labelPairs | ||
| return nil | ||
| } | ||
|
|
||
| func makeLabelPairs(names, values []string) []*prometheusgo.LabelPair { | ||
| pairs := make([]*prometheusgo.LabelPair, len(names)) | ||
| for i := range names { | ||
| n := names[i] | ||
| v := values[i] | ||
| pairs[i] = &prometheusgo.LabelPair{Name: &n, Value: &v} | ||
| } | ||
| return pairs | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
do we need cardinality protection here?
Without any limit, a caller passing user-controlled label values (e.g., SQL query fingerprints, user IDs) could cause unbounded memory growth. Consider:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Prometheus doesn't do bounding on cardinality (link), does it feel okay to match that pattern, and push bounding up to the consumers of the library?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ah cool, yeah that sounds fine