Skip to content

Commit

Permalink
Improve matching regexp to avoid situation where it matches everything (
Browse files Browse the repository at this point in the history
#34)

Signed-off-by: Augustin Husson <[email protected]>
  • Loading branch information
Nexucis authored Dec 5, 2024
1 parent 21fce0b commit 58c1c2d
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
18 changes: 16 additions & 2 deletions database/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -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]()
Expand All @@ -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.
Expand Down Expand Up @@ -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
}
9 changes: 9 additions & 0 deletions database/database_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
}

0 comments on commit 58c1c2d

Please sign in to comment.