This repository has been archived by the owner on Oct 2, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
execute.go
158 lines (128 loc) · 3.39 KB
/
execute.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
package grim
// Copyright 2015 MediaMath <http://www.mediamath.com>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
import (
"bufio"
"fmt"
"io"
"os"
"os/exec"
"sync"
"syscall"
"time"
)
var errTimeout = fmt.Errorf("build timed out")
type eitherStringOrError struct {
str string
err error
}
func execute(env []string, workingDir string, execPath string, timeout time.Duration, args ...string) (*executeResult, error) {
outputChan := make(chan string)
res, err := executeWithOutputChan(outputChan, env, workingDir, execPath, timeout, args...)
if err != nil {
return nil, err
}
out := ""
for line := range outputChan {
out += fmt.Sprintf("%v\n", line)
}
res.Output = out
return res, nil
}
func executeWithOutputChan(outputChan chan string, env []string, workingDir string, execPath string, timeout time.Duration, args ...string) (*executeResult, error) {
startTime := time.Now()
cmd := exec.Command(execPath, args...)
cmd.Dir = workingDir
cmd.Env = env
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
var startErr error
if outputChan != nil {
var wg sync.WaitGroup
outReader, orErr := cmd.StdoutPipe()
if orErr != nil {
return nil, fmt.Errorf("error capturing stdout: %v", orErr)
}
errReader, erErr := cmd.StderrPipe()
if erErr != nil {
return nil, fmt.Errorf("error capturing stderr: %v", erErr)
}
wg.Add(2)
go sendLines(outReader, outputChan, &wg)
go sendLines(errReader, outputChan, &wg)
go closeAfterDone(outputChan, &wg)
}
startErr = cmd.Start()
if startErr != nil {
return nil, fmt.Errorf("error starting process: %v", startErr)
}
exitCode, err := killProcessOnTimeout(cmd, timeout)
if err != nil {
return nil, err
}
return &executeResult{
StartTime: startTime,
EndTime: time.Now(),
SysTime: cmd.ProcessState.SystemTime(),
UserTime: cmd.ProcessState.UserTime(),
InitialEnv: cmd.Env,
ExitCode: exitCode,
}, nil
}
// kills a cmd process based on config timeout settings
func killProcessOnTimeout(cmd *exec.Cmd, timeout time.Duration) (exitCode int, err error) {
// 1 deep channel for done
done := make(chan error, 1)
go func() {
done <- cmd.Wait()
}()
processGroupID, err := syscall.Getpgid(cmd.Process.Pid)
if err != nil {
return 0, err
}
grimProcessGroupID, err := syscall.Getpgid(os.Getpid())
if err != nil {
return 0, err
}
select {
case <-time.After(timeout):
exitCode = -23
err = errTimeout
case err := <-done:
if err != nil {
exitCode, err = getExitCode(err)
if err != nil {
return 0, fmt.Errorf("Build Error: %v", err)
}
}
}
if grimProcessGroupID != processGroupID {
syscall.Kill(-processGroupID, syscall.SIGKILL)
}
return
}
// gets the exit code from error
func getExitCode(err error) (int, error) {
var exitCode int
if exitErr, ok := err.(*exec.ExitError); ok {
if status, ok := exitErr.Sys().(syscall.WaitStatus); ok {
exitCode = status.ExitStatus()
} else {
return 0, fmt.Errorf("Wrong Wait Status: %v", err)
}
} else {
return 0, fmt.Errorf("Can not cast to ExitError: %v", err)
}
return exitCode, nil
}
func sendLines(rc io.ReadCloser, linesChan chan string, wg *sync.WaitGroup) {
scanner := bufio.NewScanner(rc)
for scanner.Scan() {
linesChan <- scanner.Text()
}
wg.Done()
}
func closeAfterDone(outputChan chan string, wg *sync.WaitGroup) {
wg.Wait()
close(outputChan)
}