Skip to content
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

prometheus: prevent panic when incrmenting counter #146

Merged
merged 1 commit into from
Nov 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions prometheus/prometheus.go
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,13 @@ func (p *PrometheusSink) IncrCounterWithLabels(parts []string, val float32, labe
key, hash := flattenKey(parts, labels)
pc, ok := p.counters.Load(hash)

// Prometheus Counter.Add() panics if val < 0. We don't want this to
// cause applications to crash, so log an error instead.
if val < 0 {
log.Printf("[ERR] Attempting to increment Prometheus counter %v with value negative value %v", key, val)
return
}

// Does the counter exist?
if ok {
localCounter := *pc.(*counter)
Expand Down
8 changes: 8 additions & 0 deletions prometheus/prometheus_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,9 @@ func TestDefinitions(t *testing.T) {
sink.AddSample(summaryDef.Name, 42)
sink.IncrCounter(counterDef.Name, 1)

// Prometheus panic should not be propagated
sink.IncrCounter(counterDef.Name, -1)

// Test that the expiry behavior works as expected. First pick a time which
// is after all the actual updates above.
timeAfterUpdates := time.Now()
Expand Down Expand Up @@ -359,6 +362,11 @@ func TestDefinitionsWithLabels(t *testing.T) {
}
return true
})

// Prometheus panic should not be propagated
sink.IncrCounterWithLabels(counterDef.Name, -1, []metrics.Label{
{Name: "version", Value: "some info"},
})
}

func TestMetricSinkInterface(t *testing.T) {
Expand Down