From 88f3f86c7c9f9316cb48f5e4a30d156b0d17370b Mon Sep 17 00:00:00 2001 From: ppom <> Date: Fri, 24 Mar 2023 00:49:59 +0100 Subject: [PATCH] Close #2 --- conf.go | 28 +++++++++++++++++++++++++--- main.go | 6 +++++- reaction.yml | 11 ----------- 3 files changed, 30 insertions(+), 15 deletions(-) diff --git a/conf.go b/conf.go index 78e97eb..b6bc164 100644 --- a/conf.go +++ b/conf.go @@ -6,6 +6,7 @@ import ( "log" "os" "regexp" + "time" "gopkg.in/yaml.v3" ) @@ -21,30 +22,51 @@ type Stream struct { type Filter struct { Regex []string - compiledRegex []regexp.Regexp + compiledRegex []regexp.Regexp // Computed after YAML parsing Retry uint RetryPeriod string `yaml:"retry-period"` + retryDuration time.Duration // Computed after YAML parsing Actions map[string]*Action } type Action struct { - name, filterName, streamName string + name, filterName, streamName string // Computed after YAML parsing Cmd []string After string `yaml:",omitempty"` + afterDuration time.Duration // Computed after YAML parsing } func (c *Conf) setup() { for streamName, stream := range c.Streams { for filterName, filter := range stream.Filters { + + // Parse Duration + retryDuration, err := time.ParseDuration(filter.RetryPeriod) + if err != nil { + log.Fatalln("Failed to parse time in configuration file:", err) + } + filter.retryDuration = retryDuration + // Compute Regexes for _, regex := range filter.Regex { filter.compiledRegex = append(filter.compiledRegex, *regexp.MustCompile(regex)) } - // Give all relevant infos to Actions + for actionName, action := range filter.Actions { + + // Give all relevant infos to Actions action.name = actionName action.filterName = filterName action.streamName = streamName + + // Parse Duration + if action.After != "" { + afterDuration, err := time.ParseDuration(action.After) + if err != nil { + log.Fatalln("Failed to parse time in configuration file:", err) + } + action.afterDuration = afterDuration + } } } } diff --git a/main.go b/main.go index bd881b0..b258442 100644 --- a/main.go +++ b/main.go @@ -3,6 +3,7 @@ package main import ( "bufio" "log" + "time" "os/exec" ) @@ -49,7 +50,10 @@ func (f *Filter) launch(line *string) { } func (a *Action) launch(line *string) { - log.Printf("INFO %s.%s.%s: line {%s} → run {%s}\n", a.streamName, a.filterName, a.name, *line, a.Cmd) + if a.afterDuration != 0 { + time.Sleep(a.afterDuration) + } + log.Printf("INFO %s.%s.%s: line {%s} → run %s\n", a.streamName, a.filterName, a.name, *line, a.Cmd) cmd := exec.Command(a.Cmd[0], a.Cmd[1:]...) if ret := cmd.Run(); ret != nil { diff --git a/reaction.yml b/reaction.yml index 7459e09..8f72d21 100644 --- a/reaction.yml +++ b/reaction.yml @@ -21,14 +21,3 @@ streams: sleepdamn: cmd: [ "echo", "sleepDAMN" ] after: 2s - - # - cmd: journalctl -fu phpfpm-nextcloud.service - # filters: - # - regex: - # - '"message":"Login failed: .\+ (Remote IP: )"' - # retry: 3 - # retry-period: 1h - # actions: - # - cmd: *iptablesban - # - cmd: *iptablesunban - # after: 1h