Fix crash when all the regexes of a filter have no pattern in them

Fix #66
Example configuration causing crash:
```yaml
streams:
  mongod_restart:
    cmd: [ 'sh', '-c', 'while true; do echo "Started MongoDB Database Server."; sleep 5; done' ]
    filters:
      mongo_restart:
        regex:
          - 'Started MongoDB Database Server.'
        actions:
          restart_chat_tel:
            cmd: [ 'systemctl', 'restart', 'nginx' ]
```
This commit is contained in:
ppom 2024-01-09 12:00:00 +01:00
parent 2b2275c547
commit af2f092b71

View File

@ -76,12 +76,18 @@ func (f *Filter) match(line *string) string {
if matches := regex.FindStringSubmatch(*line); matches != nil { if matches := regex.FindStringSubmatch(*line); matches != nil {
if f.pattern != nil {
match := matches[regex.SubexpIndex(f.pattern.name)] match := matches[regex.SubexpIndex(f.pattern.name)]
if f.pattern.notAnIgnore(&match) { if f.pattern.notAnIgnore(&match) {
logger.Printf(logger.INFO, "%s.%s: match [%v]\n", f.stream.name, f.name, match) logger.Printf(logger.INFO, "%s.%s: match [%v]\n", f.stream.name, f.name, match)
return match return match
} }
} else {
logger.Printf(logger.INFO, "%s.%s: match [.]\n", f.stream.name, f.name)
// No pattern, so this match will never actually be used
return "."
}
} }
} }
return "" return ""
@ -96,10 +102,17 @@ func (f *Filter) sendActions(match string, at time.Time) {
func (a *Action) exec(match string) { func (a *Action) exec(match string) {
defer wgActions.Done() defer wgActions.Done()
var computedCommand []string
if a.filter.pattern != nil {
computedCommand := make([]string, 0, len(a.Cmd)) computedCommand := make([]string, 0, len(a.Cmd))
for _, item := range a.Cmd { for _, item := range a.Cmd {
computedCommand = append(computedCommand, strings.ReplaceAll(item, a.filter.pattern.nameWithBraces, match)) computedCommand = append(computedCommand, strings.ReplaceAll(item, a.filter.pattern.nameWithBraces, match))
} }
} else {
computedCommand = a.Cmd
}
logger.Printf(logger.INFO, "%s.%s.%s: run %s\n", a.filter.stream.name, a.filter.name, a.name, computedCommand) logger.Printf(logger.INFO, "%s.%s.%s: run %s\n", a.filter.stream.name, a.filter.name, a.name, computedCommand)