This repository has been archived by the owner on Oct 11, 2023. It is now read-only.
/
tasksetting.go
92 lines (76 loc) · 2.33 KB
/
tasksetting.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
package models
import (
"context"
"fmt"
"os"
"os/exec"
"strconv"
"time"
)
// TaskSetting is the setting data model of A01Task
type TaskSetting struct {
Version string `json:"ver,omitempty"`
Execution map[string]string `json:"execution,omitempty"`
Classifier map[string]string `json:"classifier,omitempty"`
Miscellanea map[string]string `json:"misc,omitempty"`
}
// GetIdentifier returns the unique identifier of the task setting
func (setting *TaskSetting) GetIdentifier() string {
return setting.Classifier["identifier"]
}
// Execute runs the command and returns the execution results
func (setting *TaskSetting) Execute() (result string, duration int, output []byte) {
shellExec := "/bin/bash"
if _, err := os.Stat("/bin/bash"); os.IsNotExist(err) {
shellExec = "/bin/sh"
}
timeout := time.Hour * 2
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
execution := []string{"-c", setting.Execution["command"]}
cmd := exec.CommandContext(ctx, shellExec, execution...)
begin := time.Now()
output, err := cmd.CombinedOutput()
elapsed := time.Since(begin)
duration = int(elapsed.Seconds())
if err == nil {
result = "Passed"
} else {
if elapsed >= timeout {
result = "Timeout"
} else {
result = "Failed"
}
}
return
}
// CreateCompletedTask returns an uncommitted Task instance which represents a completed task
func (setting *TaskSetting) CreateCompletedTask(result string, duration int, podName string, runID string) *TaskResult {
nRunID, _ := strconv.Atoi(runID)
task := TaskResult{
Name: fmt.Sprintf("Test: %s", setting.GetIdentifier()),
Duration: duration,
Result: result,
ResultDetails: map[string]interface{}{"agent": podName},
RunID: nRunID,
Settings: *setting,
Status: "Completed",
}
return &task
}
// CreateUncompletedTask returns an uncommitted Task instance which represents an incomplete task.
func (setting *TaskSetting) CreateUncompletedTask(podName string, runID string, errorMsg string) *TaskResult {
nRunID, _ := strconv.Atoi(runID)
task := TaskResult{
Name: fmt.Sprintf("Test: %s", setting.GetIdentifier()),
Result: "Error",
ResultDetails: map[string]interface{}{
"agent": podName,
"error": errorMsg,
},
RunID: nRunID,
Settings: *setting,
Status: "Error",
}
return &task
}