-
Notifications
You must be signed in to change notification settings - Fork 0
/
task.go
209 lines (198 loc) · 4.66 KB
/
task.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
package main
import (
"fmt"
"os"
"os/exec"
"reflect"
"regexp"
"slices"
"strings"
"sync"
"time"
"github.com/goccy/go-json"
"github.com/gofiber/fiber/v2"
)
var logEntryDirRegex = regexp.MustCompile(`^\d\d\d\d\d\d.\d\d\d\d\d\d$`)
var tsLogFormat = "060102.150405"
type jsonTest struct {
Key string `yaml:"Key"`
Value any `yaml:"Value"`
path *json.Path
}
func (t *jsonTest) Test(b json.RawMessage) (pass bool) {
var err error
if t.path == nil {
t.path, err = json.CreatePath(t.Key)
if err != nil {
return
}
}
rt := reflect.TypeOf(t.Value)
if rt.Kind() == reflect.String {
tv := t.Value.(string)
v := tv
err = t.path.Unmarshal(b, &v)
if err != nil {
return false
}
return reflect.DeepEqual(tv, v)
}
if rt.Kind() >= reflect.Int && rt.Kind() <= reflect.Uint64 {
tv := t.Value.(int)
v := tv
err = t.path.Unmarshal(b, &v)
if err != nil {
return false
}
return reflect.DeepEqual(tv, v)
}
if rt.Kind() >= reflect.Float32 && rt.Kind() <= reflect.Float64 {
tv := t.Value.(float64)
v := tv
err = t.path.Unmarshal(b, &v)
if err != nil {
return false
}
return reflect.DeepEqual(tv, v)
}
if rt.Kind() == reflect.Bool {
tv := t.Value.(bool)
v := tv
err = t.path.Unmarshal(b, &v)
if err != nil {
return false
}
return reflect.DeepEqual(tv, v)
}
return
}
type tests struct {
Header map[string]string `yaml:"Header"`
JSONBody []jsonTest `yaml:"JSONBody"`
}
func (t tests) Test(c *fiber.Ctx) (shouldRun bool) {
var strValue string
for key, value := range t.Header {
strValue = c.Get(key)
if strValue != value {
return
}
}
if len(t.JSONBody) > 0 && strings.HasPrefix(c.Get("Content-Type"), "application/json") {
reqBody := c.Body()
for _, t := range t.JSONBody {
if !t.Test(reqBody) {
return
}
}
}
return true
}
type Task struct {
RunnerExecutable string `yaml:"RunnerExecutable"`
Args []string `yaml:"Args"`
MaxRunSeconds int `yaml:"MaxRunSeconds"`
TaskKey string `yaml:"TaskKey"`
Route string `yaml:"Route"`
Tests tests `yaml:"Tests"`
logsDir string
mu sync.Mutex
runningDeadline *time.Time
}
func (t *Task) startTask() (ts time.Time, err error) {
ts = time.Now()
if t.runningDeadline != nil && t.runningDeadline.After(ts) {
err = fmt.Errorf("current task is still running until %q", t.runningDeadline)
return
}
t.mu.Lock()
deadline := ts.Add(time.Duration(t.MaxRunSeconds) * time.Second)
t.runningDeadline = &deadline
t.mu.Unlock()
return
}
func (t *Task) executeCmd(cmd *exec.Cmd) {
err := cmd.Run()
if err != nil {
cmd.Stderr.Write([]byte("\n" + err.Error()))
}
t.mu.Lock()
t.runningDeadline = nil
t.mu.Unlock()
}
func (t *Task) ShouldRun(c *fiber.Ctx) (shouldRun bool) {
return t.Tests.Test(c)
}
func (t *Task) Run() (logPrefix string, err error) {
ts, err := t.startTask()
if err != nil {
return
}
logPrefix = ts.Format(tsLogFormat)
dir := "logs/" + t.TaskKey + "/" + logPrefix
err = os.MkdirAll(dir, 0755)
if err != nil {
return
}
outFile, err := os.OpenFile(dir+"/out.log", os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
return
}
errFile, err := os.OpenFile(dir+"/err.log", os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
return
}
cmd := exec.Command(t.RunnerExecutable, t.Args...)
cmd.Stdout = outFile
cmd.Stderr = errFile
cmd.WaitDelay = time.Second * time.Duration(t.MaxRunSeconds)
go t.executeCmd(cmd)
return
}
func (t *Task) DirBrowser(routePrefix string) func(c *fiber.Ctx) (err error) {
return func(c *fiber.Ctx) (err error) {
files, err := os.ReadDir(t.logsDir)
if err != nil {
return
}
usedRoutePrefix := routePrefix
if len(routePrefix) > 0 {
if !strings.HasSuffix(routePrefix, "/") {
usedRoutePrefix = "/" + routePrefix
}
}
dirs := make([]string, 0, len(files))
for _, f := range files {
if f.IsDir() && logEntryDirRegex.MatchString(f.Name()) {
dir := f.Name()
ts, err := time.Parse(tsLogFormat, dir)
if err != nil {
continue
}
li := fmt.Sprintf("<li><a href=\"%s/logs/%s/%s\">%s</a></li>",
usedRoutePrefix, t.TaskKey, dir, ts.Format("2006-01-02 15:04:05"),
)
dirs = append(dirs, li)
}
}
slices.Sort(dirs)
slices.Reverse(dirs)
c.Set("Content-Type", "text/html")
html := fmt.Sprintf("<html><head><title>%s</title></head>"+
"<body><h1>Log entries for %s</h1><ul>%s</ul></body></html>",
t.TaskKey, t.TaskKey, strings.Join(dirs, ""),
)
return c.SendString(html)
}
}
func (t *Task) Validate() (err error) {
if len(t.Tests.JSONBody) > 0 {
for _, e := range t.Tests.JSONBody {
e.path, err = json.CreatePath(e.Key)
if err != nil {
return
}
}
}
return
}