Skip to content

Commit 005b3e7

Browse files
author
Emilien Kenler
committed
Compile the regexp outside of the loop
1 parent 9123e2f commit 005b3e7

File tree

2 files changed

+27
-9
lines changed

2 files changed

+27
-9
lines changed

collectd/checker.go

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ package collectd
33
import (
44
"bytes"
55
"fmt"
6-
"regexp"
76
"strings"
87
"sync"
98
"sync/atomic"
@@ -91,17 +90,19 @@ func (checker *Checker) checkRecord(record CollectdRecord) ([]shared.CheckResult
9190

9291
// Load host specific thresholds
9392
for pattern, threshold := range rule.Check.HostThresholds {
94-
matched, err := regexp.MatchString(pattern, record.Host)
95-
if err != nil {
96-
checker.logger.Error(err)
93+
if threshold.Regexp == nil {
9794
continue
9895
}
99-
if matched {
100-
matchName = fmt.Sprintf("host:%s", pattern)
101-
critical = threshold.Critical
102-
warning = threshold.Warning
103-
break
96+
97+
if !threshold.Regexp.MatchString(record.Host) {
98+
continue
10499
}
100+
101+
matchName = fmt.Sprintf("host:%s", pattern)
102+
103+
critical = threshold.Critical
104+
warning = threshold.Warning
105+
break
105106
}
106107

107108
// CRITICAL CHECK

config/config.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package config
33
import (
44
"fmt"
55
"io/ioutil"
6+
"regexp"
67
"text/template"
78

89
"github.com/hashicorp/hcl"
@@ -23,6 +24,7 @@ type CheckThreshold struct {
2324
CriticalTpl string `hcl:"critical"`
2425
Warning hil.EvaluationResult `hcl:"-"`
2526
Critical hil.EvaluationResult `hcl:"-"`
27+
Regexp *regexp.Regexp `hcl:"-"`
2628
}
2729

2830
type CheckThresholdMap map[string]CheckThreshold
@@ -44,6 +46,18 @@ func (m CheckThresholdMap) Parse(hilConfig *hil.EvalConfig) (err error) {
4446
return
4547
}
4648

49+
func (m CheckThresholdMap) CompileRegexp() error {
50+
for pattern, threshold := range m {
51+
r, err := regexp.Compile(pattern)
52+
if err != nil {
53+
return err
54+
}
55+
threshold.Regexp = r
56+
m[pattern] = threshold
57+
}
58+
return nil
59+
}
60+
4761
type Check struct {
4862
Plugin string `hcl:"plugin"`
4963
PluginInstance string `hcl:"plugin_instance"`
@@ -121,6 +135,9 @@ func loadFileHcl(root string) (*Config, error) {
121135
}
122136

123137
check.HostThresholds.Parse(hilConfig)
138+
if err := check.HostThresholds.CompileRegexp(); err != nil {
139+
return nil, err
140+
}
124141
check.MetaThresholds.Parse(hilConfig)
125142

126143
out.Checks[name] = check

0 commit comments

Comments
 (0)