reaction/main.go

87 lines
1.8 KiB
Go
Raw Normal View History

2023-03-19 23:10:18 +01:00
package main
import (
2023-03-20 23:25:57 +01:00
"bufio"
2023-03-19 23:10:18 +01:00
"log"
2023-03-24 00:49:59 +01:00
"time"
2023-03-19 23:10:18 +01:00
"os/exec"
)
2023-03-24 00:27:51 +01:00
func cmdStdout(commandline []string) chan string {
lines := make(chan string)
2023-03-19 23:10:18 +01:00
2023-03-24 00:27:51 +01:00
go func() {
cmd := exec.Command(commandline[0], commandline[1:]...)
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Fatal("couldn't open stdout on command:", err)
}
if err := cmd.Start(); err != nil {
log.Fatal("couldn't start command:", err)
}
defer stdout.Close()
2023-03-20 23:25:57 +01:00
2023-03-24 00:27:51 +01:00
scanner := bufio.NewScanner(stdout)
for scanner.Scan() {
lines <- scanner.Text()
}
close(lines)
}()
return lines
2023-03-19 23:10:18 +01:00
}
2023-03-24 00:27:51 +01:00
func (f *Filter) match(line string) bool {
log.Printf("trying to match line {%s}...\n", line)
for _, regex := range f.compiledRegex {
log.Printf("...on %s\n", regex.String())
if match := regex.FindString(line); match != "" {
log.Printf("match `%v` in line: `%v`\n", regex.String(), line)
return true
}
2023-03-20 23:25:57 +01:00
}
2023-03-24 00:27:51 +01:00
return false
2023-03-20 23:25:57 +01:00
}
2023-03-24 00:27:51 +01:00
func (f *Filter) launch(line *string) {
for _, a := range f.Actions {
go a.launch(line)
2023-03-19 23:10:18 +01:00
}
2023-03-24 00:27:51 +01:00
}
2023-03-20 23:25:57 +01:00
2023-03-24 00:27:51 +01:00
func (a *Action) launch(line *string) {
2023-03-24 00:49:59 +01:00
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)
2023-03-20 23:25:57 +01:00
2023-03-24 00:27:51 +01:00
cmd := exec.Command(a.Cmd[0], a.Cmd[1:]...)
if ret := cmd.Run(); ret != nil {
log.Printf("ERR %s.%s.%s: line {%s} → run %s, code {%s}\n", a.streamName, a.filterName, a.name, *line, a.Cmd, ret)
2023-03-19 23:10:18 +01:00
}
}
2023-03-24 00:27:51 +01:00
func (s *Stream) handle() {
log.Printf("streamHandle{%v}: start\n", s.Cmd)
lines := cmdStdout(s.Cmd)
for line := range lines {
for _, filter := range s.Filters {
if filter.match(line) {
filter.launch(&line)
2023-03-19 23:10:18 +01:00
}
}
2023-03-24 00:27:51 +01:00
}
2023-03-19 23:10:18 +01:00
}
func main() {
2023-03-23 21:14:53 +01:00
conf := parseConf("./reaction.yml")
2023-03-24 00:27:51 +01:00
for _, stream := range conf.Streams {
go stream.handle()
}
// Infinite wait
<-make(chan bool)
2023-03-19 23:10:18 +01:00
}