-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtask.go
93 lines (87 loc) · 2.28 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
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
"os/exec"
"time"
)
var (
ErrEmptyUrl = errors.New(`URL is empty`)
ErrBadStatus = errors.New(`Status is not 200`)
ErrNotJson = errors.New(`Is not JSON`)
)
type Task struct {
Command []string `json:"command"`
RespondUrl string `json:"respond_url"`
ImmediatelyNext bool `json:"immediately_next"`
}
func GetTask(url string) (*Task, error) {
if url == `` {
ErrorLog.Println(ErrEmptyUrl)
return nil, ErrEmptyUrl
}
request, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
ErrorLog.Println(err.Error())
return nil, err
}
client := http.Client{ Timeout: time.Second * 3 }
defer client.CloseIdleConnections()
response, err := client.Do(request)
if err != nil {
ErrorLog.Println(err.Error())
return nil, err
}
defer response.Body.Close()
if response.StatusCode != 200 {
ErrorLog.Println(response.Status)
return nil, ErrBadStatus
}
if contentType := response.Header.Get(`Content-Type`); contentType != `application/json` {
ErrorLog.Println(contentType)
return nil, ErrNotJson
}
task := Task{}
decoder := json.NewDecoder(response.Body)
if err := decoder.Decode(&task); err != nil {
ErrorLog.Println(err.Error())
return nil, err
}
DebugLog.Println(`Got task`, task)
return &task, nil
}
func ExecTask(task *Task) ([]byte, int, time.Duration, error) {
start := time.Now()
cmd := exec.Command(task.Command[0], task.Command[1:]...)
stdoutStderr, err := cmd.CombinedOutput()
if err != nil {
ErrorLog.Println(err.Error())
return nil, 0, 0, err
}
spent := time.Now().Sub(start)
return stdoutStderr, cmd.ProcessState.ExitCode(), spent, nil
}
func RespondTask(respondUrl string, data []byte, exitCode int, spent time.Duration) {
DebugLog.Println(`Sending response to`, respondUrl)
buffer := bytes.NewBuffer(data)
request, err := http.NewRequest(http.MethodPost, respondUrl, buffer)
if err != nil {
ErrorLog.Println(err.Error())
return
}
request.Header.Add(`EXIT_CODE`, fmt.Sprintf(`%d`, exitCode))
request.Header.Add(`SPENT`, spent.String())
client := http.Client{}
response, err := client.Do(request)
if err != nil {
ErrorLog.Println(err.Error())
return
}
defer response.Body.Close()
if response.StatusCode != 200 {
ErrorLog.Println(respondUrl, response.Status)
}
}