-
Notifications
You must be signed in to change notification settings - Fork 0
/
action.go
89 lines (67 loc) · 1.5 KB
/
action.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package main
import (
"bytes"
"fmt"
"os/exec"
"text/template"
"github.com/vasyahuyasa/botassasin/log"
)
type cmdParams map[string]string
type action struct {
params []*template.Template
}
func newAction(parmTpls []string) (*action, error) {
var tpls []*template.Template
for i, tplCmd := range parmTpls {
tpl, err := template.New(fmt.Sprintf("param_%d", i)).Parse(tplCmd)
if err != nil {
return nil, fmt.Errorf("cannot parse command template %v: %w", tpl, err)
}
tpls = append(tpls, tpl)
}
return &action{
params: tpls,
}, nil
}
func (a *action) Execute(l logLine) error {
// no action
if len(a.params) == 0 {
return nil
}
strCmd, cmdParams, err := a.formatCmdTpl(l)
if err != nil {
return fmt.Errorf("cannot format command template: %w", err)
}
buf := bytes.NewBuffer([]byte{})
cmd := exec.Command(strCmd, cmdParams...)
cmd.Stdout = buf
cmd.Stderr = buf
err = cmd.Run()
if buf.Len() != 0 {
log.Println("action output:", buf.String())
}
return err
}
func (a *action) formatCmdTpl(l logLine) (string, []string, error) {
params := cmdParams{
"ip": l.IP().String(),
}
l.EachField(func(k, v string) {
params[k] = v
})
var cmd string
var cmdParams []string
for i, tpl := range a.params {
buf := bytes.NewBuffer([]byte{})
err := tpl.Execute(buf, params)
if err != nil {
return "", nil, fmt.Errorf("param %d: %w", i, err)
}
if i == 0 {
cmd = buf.String()
} else {
cmdParams = append(cmdParams, buf.String())
}
}
return cmd, cmdParams, nil
}