From 58c1c2dfc2c197409bbecae7c7f5b71ea07fbda2 Mon Sep 17 00:00:00 2001 From: Augustin Husson Date: Thu, 5 Dec 2024 15:45:51 +0100 Subject: [PATCH] Improve matching regexp to avoid situation where it matches everything (#34) Signed-off-by: Augustin Husson --- database/database.go | 18 ++++++++++++++++-- database/database_test.go | 9 +++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/database/database.go b/database/database.go index e803c2b..ad3ce8e 100644 --- a/database/database.go +++ b/database/database.go @@ -290,7 +290,7 @@ func (d *db) matchValidMetric(validMetric string) { continue } } - if re.MatchString(validMetric) { + if isMatching(re, validMetric) { matchingMetrics := partialMetric.MatchingMetrics if matchingMetrics == nil { matchingMetrics = v1.NewSet[string]() @@ -301,7 +301,7 @@ func (d *db) matchValidMetric(validMetric string) { } } -// GenerateRegexp is taking an partial metric name, +// GenerateRegexp is taking a partial metric name, // will replace every variable by a pattern and then returning a regepx if the final string is not just equal to .*. func generateRegexp(partialMetricName string) (*common.Regexp, error) { // The first step is to replace every variable by a single special char. @@ -331,3 +331,17 @@ func generateRegexp(partialMetricName string) (*common.Regexp, error) { re, err := common.NewRegexp(fmt.Sprintf("^%s$", compileString)) return &re, err } + +func isMatching(re *common.Regexp, metric string) bool { + if !re.MatchString(metric) { + return false + } + // We are taking some time to look at what is matching. + // We are doing that to avoid the situation where this regexp `foo|` is matching everything. + for _, match := range re.FindAllString(metric, -1) { + if len(match) > 0 { + return true + } + } + return false +} diff --git a/database/database_test.go b/database/database_test.go index 188025f..526dd77 100644 --- a/database/database_test.go +++ b/database/database_test.go @@ -66,3 +66,12 @@ func TestGenerateRegexp(t *testing.T) { }) } } + +func TestIsMatching(t *testing.T) { + re, _ := generateRegexp("foo|") + assert.False(t, isMatching(re, "bar")) + assert.True(t, isMatching(re, "foo")) + + re, _ = generateRegexp("foo|bar") + assert.True(t, isMatching(re, "bar")) +}