- Notifications
You must be signed in to change notification settings - Fork1k
feat: use map instead of slice in metrics aggregator#11815
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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Uh oh!
There was an error while loading.Please reload this page.
Merged
Changes fromall commits
Commits
Show all changes
7 commits Select commitHold shift + click to select a range
b936232
feat: use map instead slice in metrics aggregator
mtojekc90a41f
fix
mtojekf407b47
add store size gauge
mtojek12fcdab
Use struct key
mtojek628e4ec
Address PR comments
mtojekbf48edc
Address Spike's feedback
mtojek4d0d889
fix test
mtojekFile filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
118 changes: 73 additions & 45 deletionscoderd/prometheusmetrics/aggregator.go
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 |
---|---|---|
@@ -2,6 +2,9 @@ package prometheusmetrics | ||
import ( | ||
"context" | ||
"fmt" | ||
"sort" | ||
"strings" | ||
"time" | ||
"github.com/prometheus/client_golang/prometheus" | ||
@@ -24,20 +27,23 @@ const ( | ||
loggerName = "prometheusmetrics" | ||
sizeCollectCh = 10 | ||
sizeUpdateCh =4096 | ||
mtojek marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
defaultMetricsCleanupInterval = 2 * time.Minute | ||
) | ||
var MetricLabelValueEncoder = strings.NewReplacer("\\", "\\\\", "|", "\\|", ",", "\\,", "=", "\\=") | ||
type MetricsAggregator struct { | ||
store map[metricKey]annotatedMetric | ||
log slog.Logger | ||
metricsCleanupInterval time.Duration | ||
collectCh chan (chan []prometheus.Metric) | ||
updateCh chan updateRequest | ||
storeSizeGauge prometheus.Gauge | ||
updateHistogram prometheus.Histogram | ||
cleanupHistogram prometheus.Histogram | ||
} | ||
@@ -64,17 +70,37 @@ type annotatedMetric struct { | ||
expiryDate time.Time | ||
} | ||
type metricKey struct { | ||
username string | ||
workspaceName string | ||
agentName string | ||
templateName string | ||
metricName string | ||
labelsStr string | ||
} | ||
func hashKey(req *updateRequest, m *agentproto.Stats_Metric) metricKey { | ||
labelPairs := make(sort.StringSlice, 0, len(m.GetLabels())) | ||
for _, label := range m.GetLabels() { | ||
if label.Value == "" { | ||
continue | ||
} | ||
labelPairs = append(labelPairs, fmt.Sprintf("%s=%s", label.Name, MetricLabelValueEncoder.Replace(label.Value))) | ||
} | ||
labelPairs.Sort() | ||
return metricKey{ | ||
username: req.username, | ||
workspaceName: req.workspaceName, | ||
agentName: req.agentName, | ||
templateName: req.templateName, | ||
metricName: m.Name, | ||
labelsStr: strings.Join(labelPairs, ","), | ||
} | ||
} | ||
var _ prometheus.Collector = new(MetricsAggregator) | ||
func (am *annotatedMetric) asPrometheus() (prometheus.Metric, error) { | ||
labels := make([]string, 0, len(agentMetricsLabels)+len(am.Labels)) | ||
labelValues := make([]string, 0, len(agentMetricsLabels)+len(am.Labels)) | ||
@@ -101,14 +127,25 @@ func NewMetricsAggregator(logger slog.Logger, registerer prometheus.Registerer, | ||
metricsCleanupInterval = duration | ||
} | ||
storeSizeGauge := prometheus.NewGauge(prometheus.GaugeOpts{ | ||
Namespace: "coderd", | ||
Subsystem: "prometheusmetrics", | ||
Name: "metrics_aggregator_store_size", | ||
Help: "The number of metrics stored in the aggregator", | ||
}) | ||
err := registerer.Register(storeSizeGauge) | ||
if err != nil { | ||
return nil, err | ||
} | ||
updateHistogram := prometheus.NewHistogram(prometheus.HistogramOpts{ | ||
Namespace: "coderd", | ||
Subsystem: "prometheusmetrics", | ||
Name: "metrics_aggregator_execution_update_seconds", | ||
Help: "Histogram for duration of metrics aggregator update in seconds.", | ||
Buckets: []float64{0.001, 0.005, 0.010, 0.025, 0.050, 0.100, 0.500, 1, 5, 10, 30}, | ||
}) | ||
err = registerer.Register(updateHistogram) | ||
if err != nil { | ||
return nil, err | ||
} | ||
@@ -129,9 +166,12 @@ func NewMetricsAggregator(logger slog.Logger, registerer prometheus.Registerer, | ||
log: logger.Named(loggerName), | ||
metricsCleanupInterval: metricsCleanupInterval, | ||
store: map[metricKey]annotatedMetric{}, | ||
collectCh: make(chan (chan []prometheus.Metric), sizeCollectCh), | ||
updateCh: make(chan updateRequest, sizeUpdateCh), | ||
storeSizeGauge: storeSizeGauge, | ||
updateHistogram: updateHistogram, | ||
cleanupHistogram: cleanupHistogram, | ||
}, nil | ||
@@ -152,32 +192,32 @@ func (ma *MetricsAggregator) Run(ctx context.Context) func() { | ||
ma.log.Debug(ctx, "update metrics") | ||
timer := prometheus.NewTimer(ma.updateHistogram) | ||
for _, m := range req.metrics { | ||
key := hashKey(&req, m) | ||
if val, ok := ma.store[key]; ok { | ||
val.Stats_Metric.Value = m.Value | ||
val.expiryDate = req.timestamp.Add(ma.metricsCleanupInterval) | ||
ma.store[key] = val | ||
} else { | ||
ma.store[key] = annotatedMetric{ | ||
Stats_Metric: m, | ||
username: req.username, | ||
workspaceName: req.workspaceName, | ||
agentName: req.agentName, | ||
templateName: req.templateName, | ||
expiryDate: req.timestamp.Add(ma.metricsCleanupInterval), | ||
} | ||
} | ||
} | ||
timer.ObserveDuration() | ||
ma.storeSizeGauge.Set(float64(len(ma.store))) | ||
case outputCh := <-ma.collectCh: | ||
ma.log.Debug(ctx, "collect metrics") | ||
output := make([]prometheus.Metric, 0, len(ma.store)) | ||
for _, m := range ma.store { | ||
promMetric, err := m.asPrometheus() | ||
if err != nil { | ||
ma.log.Error(ctx, "can't convert Prometheus value type", slog.F("name", m.Name), slog.F("type", m.Type), slog.F("value", m.Value), slog.Error(err)) | ||
@@ -191,29 +231,17 @@ func (ma *MetricsAggregator) Run(ctx context.Context) func() { | ||
ma.log.Debug(ctx, "clean expired metrics") | ||
timer := prometheus.NewTimer(ma.cleanupHistogram) | ||
now := time.Now() | ||
for key, val := range ma.store { | ||
if now.After(val.expiryDate) { | ||
delete(ma.store, key) | ||
mtojek marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
} | ||
} | ||
timer.ObserveDuration() | ||
cleanupTicker.Reset(ma.metricsCleanupInterval) | ||
ma.storeSizeGauge.Set(float64(len(ma.store))) | ||
case <-ctx.Done(): | ||
ma.log.Debug(ctx, "metrics aggregator is stopped") | ||
Oops, something went wrong.
Uh oh!
There was an error while loading.Please reload this page.
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.