reaction/main.go

97 lines
2.0 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"
"os/exec"
2023-03-20 23:25:57 +01:00
"regexp"
2023-03-19 23:10:18 +01:00
)
type Action struct {
regex, cmd []string
}
2023-03-20 23:25:57 +01:00
type compiledAction struct {
regex []regexp.Regexp
cmd []string
}
2023-03-19 23:10:18 +01:00
type Stream struct {
cmd []string
actions []Action
}
2023-03-20 23:25:57 +01:00
func compileAction(action Action) compiledAction {
var ca compiledAction
ca.cmd = action.cmd
for _, regex := range action.regex {
ca.regex = append(ca.regex, *regexp.MustCompile(regex))
}
return ca
}
/// Handle a log command
/// Must be started in a goroutine
func streamHandle(stream Stream, execQueue chan []string) {
2023-03-19 23:10:18 +01:00
log.Printf("streamHandle{%v}: start\n", stream.cmd)
2023-03-20 23:25:57 +01:00
cmd := exec.Command(stream.cmd[0], stream.cmd[1:]...)
2023-03-19 23:10:18 +01:00
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
compiledActions := make([]compiledAction, 0, len(stream.actions))
for _, action := range stream.actions {
compiledActions = append(compiledActions, compileAction(action))
}
2023-03-19 23:10:18 +01:00
scanner := bufio.NewScanner(stdout)
for scanner.Scan() {
line := scanner.Text()
2023-03-20 23:25:57 +01:00
for _, action := range compiledActions {
for _, regex := range action.regex {
if match := regex.FindString(line); match != "" {
log.Printf("match `%v` in line: `%v`\n", regex.String(), line)
execQueue <- action.cmd
}
}
}
2023-03-19 23:10:18 +01:00
}
}
2023-03-20 23:25:57 +01:00
func execQueue() chan []string {
queue := make(chan []string)
2023-03-19 23:10:18 +01:00
go func() {
for {
command := <-queue
2023-03-20 23:25:57 +01:00
cmd := exec.Command(command[0], command[1:]...)
if ret := cmd.Run(); ret != nil {
log.Printf("Error launching `%v`: code %v\n", cmd, ret)
2023-03-19 23:10:18 +01:00
}
}
}()
return queue
}
func main() {
mockstreams := []Stream{Stream{
[]string{"tail", "-f", "/home/ao/DOWN"},
[]Action{Action{
2023-03-20 23:25:57 +01:00
[]string{"prout.dev"},
[]string{"touch", "/home/ao/DAMN"},
2023-03-19 23:10:18 +01:00
}},
}}
streams := mockstreams
log.Println(streams)
queue := execQueue()
for _, stream := range streams {
go streamHandle(stream, queue)
}
2023-03-20 23:25:57 +01:00
// Infinite wait
<-make(chan bool)
2023-03-19 23:10:18 +01:00
}