/
executor.go
90 lines (70 loc) · 1.73 KB
/
executor.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
package regression
import (
"fmt"
"os/exec"
"syscall"
"time"
)
// Executor structure holds information and functionality to execute
// commands and get resource usage.
type Executor struct {
command string
args []string
out string
Executed bool
// metrics
rusage *syscall.Rusage
wall time.Duration
}
// ErrNotRun means that the command was not started
var ErrNotRun = fmt.Errorf("command still was not executed")
// ErrRusageNotAvailable means that resource usage could not be collected
var ErrRusageNotAvailable = fmt.Errorf("rusage information not available")
// NewExecutor creates a new Executor struct.
func NewExecutor(command string, args ...string) (*Executor, error) {
return &Executor{
command: command,
args: args,
}, nil
}
// Run executes the command and collects resource usage.
func (e *Executor) Run() error {
defer func() { e.Executed = true }()
cmd := exec.Command(e.command, e.args...)
start := time.Now()
out, err := cmd.CombinedOutput()
e.out = string(out)
if err != nil {
return err
}
e.wall = time.Since(start)
rusage, ok := cmd.ProcessState.SysUsage().(*syscall.Rusage)
if ok {
e.rusage = rusage
}
return nil
}
// Out retrieves stdout+stderr from the executed command.
func (e *Executor) Out() (string, error) {
if !e.Executed {
return "", ErrNotRun
}
return e.out, nil
}
// Rusage returns resource usage data.
func (e *Executor) Rusage() (*syscall.Rusage, error) {
if !e.Executed {
return nil, ErrNotRun
}
if e.rusage == nil {
return nil, ErrRusageNotAvailable
}
return e.rusage, nil
}
// Wall returns time consumed by the execution.
func (e *Executor) Wall() (time.Duration, error) {
if !e.Executed {
return 0 * time.Second, ErrNotRun
}
return e.wall, nil
}