From f49c9bb7007a5b136ed74fe1187460a184bcb795 Mon Sep 17 00:00:00 2001 From: Aliaksandr Valialkin Date: Fri, 26 Aug 2022 15:35:16 +0300 Subject: [PATCH] lib/promrelabel: optimize common regex mismatch cases for `action: replace` and `action: labelmap` --- lib/promrelabel/config.go | 1 + lib/promrelabel/relabel.go | 9 +++++++++ lib/promrelabel/relabel_timing_test.go | 4 ++-- lib/regexutil/promregex_test.go | 2 ++ 4 files changed, 14 insertions(+), 2 deletions(-) diff --git a/lib/promrelabel/config.go b/lib/promrelabel/config.go index c796a060e..346e0320a 100644 --- a/lib/promrelabel/config.go +++ b/lib/promrelabel/config.go @@ -218,6 +218,7 @@ func parseRelabelConfig(rc *RelabelConfig) (*parsedRelabelConfig, error) { regexOrig := regex if rc.Action != "replace_all" && rc.Action != "labelmap_all" { regex = regexutil.RemoveStartEndAnchors(regex) + regexOrig = regex regex = "^(?:" + regex + ")$" } re, err := regexp.Compile(regex) diff --git a/lib/promrelabel/relabel.go b/lib/promrelabel/relabel.go index 09f44b59e..c60c3ff89 100644 --- a/lib/promrelabel/relabel.go +++ b/lib/promrelabel/relabel.go @@ -203,6 +203,11 @@ func (prc *parsedRelabelConfig) apply(labels []prompbmarshal.Label, labelsOffset return labels } } + if !prc.regex.MatchString(bytesutil.ToUnsafeString(bb.B)) { + // Fast path - regexp mismatch. + relabelBufPool.Put(bb) + return labels + } match := prc.RegexAnchored.FindSubmatchIndex(bb.B) if match == nil { // Fast path - nothing to replace. @@ -388,6 +393,10 @@ func (prc *parsedRelabelConfig) replaceFullString(s, replacement string, hasCapt } } } + if !prc.regex.MatchString(s) { + // Fast path - regex mismatch + return s, false + } // Slow path - regexp processing match := prc.RegexAnchored.FindStringSubmatchIndex(s) if match == nil { diff --git a/lib/promrelabel/relabel_timing_test.go b/lib/promrelabel/relabel_timing_test.go index ff3ae373a..6e7d55d19 100644 --- a/lib/promrelabel/relabel_timing_test.go +++ b/lib/promrelabel/relabel_timing_test.go @@ -497,7 +497,7 @@ func BenchmarkApplyRelabelConfigs(b *testing.B) { pcs := mustParseRelabelConfigs(` - action: drop source_labels: [id] - regex: yes + regex: "yes" `) labelsOrig := []prompbmarshal.Label{ { @@ -584,7 +584,7 @@ func BenchmarkApplyRelabelConfigs(b *testing.B) { pcs := mustParseRelabelConfigs(` - action: keep source_labels: [id] - regex: yes + regex: "yes" `) labelsOrig := []prompbmarshal.Label{ { diff --git a/lib/regexutil/promregex_test.go b/lib/regexutil/promregex_test.go index 2a2a86351..20a04312a 100644 --- a/lib/regexutil/promregex_test.go +++ b/lib/regexutil/promregex_test.go @@ -87,4 +87,6 @@ func TestPromRegex(t *testing.T) { f(".*(a|b).*", "xa", true) f(".*(a|b).*", "xay", true) f(".*(a|b).*", "xzy", false) + f("^(?:true)$", "true", true) + f("^(?:true)$", "false", false) }