-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconcurry.go
221 lines (189 loc) · 5.48 KB
/
concurry.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
210
211
212
213
214
215
216
217
218
219
220
221
package main
import (
"bufio"
"container/ring"
"context"
"flag"
"fmt"
"log"
"math"
"os"
"os/exec"
"strings"
"sync"
"time"
)
type configType struct {
displayStdout *bool
displayStderr *bool
verbose *bool
failFast *bool
colorize *bool
repeatCount *uint
repeatConcurrent *bool
commandTimeout *uint64
xargsMode *bool
}
// TODO:
// type ColorRing struct {
// colorReset
// }
var config configType
var colors = ring.New(6)
var results = []string{}
var resultsMutex = &sync.Mutex{}
var colorReset = "\033[0m"
// initColorRing initializes an array containing color codes for terminals to
// output different colors for different Commands.
func initColorRing() {
r := colors
r.Value = "\033[31m" // red
r = r.Next()
r.Value = "\033[32m" // green
r = r.Next()
r.Value = "\033[33m" // yellow
r = r.Next()
r.Value = "\033[34m" // blue
r = r.Next()
r.Value = "\033[35m" // purple
r = r.Next()
r.Value = "\033[36m" // cyan
}
func getNextColor() string {
colors = colors.Next()
return colors.Value.(string)
}
type taskLogger struct {
taskID int
color string
}
func (t taskLogger) Sprintf(format string, args ...interface{}) string {
if *config.colorize {
format = fmt.Sprintf("%s(Task-%d) %s%s", t.color, t.taskID, format, colorReset)
} else {
format = fmt.Sprintf("(Task-%d) %s", t.taskID, format)
}
return fmt.Sprintf(format, args...)
}
// RunCmd TODO: Comment
// Note: log.Println() functions are goroutine safe. There is mutex involved when
// write() is called.
func RunCmd(command string, taskID int, wg *sync.WaitGroup, color string) {
defer wg.Done()
startTime := time.Now()
taskLogger := taskLogger{taskID: taskID, color: color}
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(*config.commandTimeout)*time.Second)
defer cancel()
if *config.verbose {
log.Println(taskLogger.Sprintf("Executing '%s'", command))
}
// We used bash here as command may contain commands that contains single/double
// quotes in them like python -c '......'. In that case, shell is responsible for
// parsing those correctly as a simply string.Split will not suffice. That is why
// we leave argument parsing to shell
// TODO: A better solution might be to detect the current running shell and run
// the command under that shell.
cmd := exec.CommandContext(ctx, "bash", "-c", command)
stdoutReader, _ := cmd.StdoutPipe()
stderrReader, _ := cmd.StderrPipe()
// TODO: err handling of above
stdoutScanner := bufio.NewScanner(stdoutReader)
stderrScanner := bufio.NewScanner(stderrReader)
init := make(chan bool)
stdErrOutput := ""
go func() {
init <- true
for stderrScanner.Scan() {
if *config.displayStderr {
log.Println(taskLogger.Sprintf("%s", stderrScanner.Text()))
} else {
// we might print this on failure
stdErrOutput += taskLogger.Sprintf("%s", stderrScanner.Text()) + "\n"
}
}
}()
<-init
cmd.Start()
if *config.displayStdout {
for stdoutScanner.Scan() {
log.Println(taskLogger.Sprintf("%s", stdoutScanner.Text()))
}
}
err := cmd.Wait()
if err != nil {
errStr := fmt.Sprintf("%s", err)
if ctx.Err() == context.DeadlineExceeded {
errStr = "Task Timeout"
} else {
log.Println(stdErrOutput)
}
failure := taskLogger.Sprintf("'%s' failed. [%s] [%s]", command,
errStr, time.Since(startTime))
if *config.failFast {
log.Println(failure)
os.Exit(1)
}
resultsMutex.Lock()
results = append(results, failure)
resultsMutex.Unlock()
} else {
if *config.verbose {
resultsMutex.Lock()
results = append(results, taskLogger.Sprintf("'%s' succeeded. [%s]",
command, time.Since(startTime)))
resultsMutex.Unlock()
}
}
}
func main() {
var wg sync.WaitGroup
startTime := time.Now()
initColorRing()
config.displayStdout = flag.Bool("o", true, "display stdout")
config.displayStderr = flag.Bool("e", true, "display stderr")
config.xargsMode = flag.Bool("x", false, "disables all concurrency and run commands like xargs")
//config.bufferIO = flag.Bool("b", false, "buffer stdout/stderr") // TODO
config.verbose = flag.Bool("v", true, "show executed command and return values")
config.repeatCount = flag.Uint("n", 1, "repeat command N times (default: synchronous, or asynchronous if -rc is set)")
config.failFast = flag.Bool("f", true, "fail if any concurrent command fails")
config.colorize = flag.Bool("c", true, "colorize the command outputs")
config.repeatConcurrent = flag.Bool("rc", false, "run repeated commands concurrently")
// used MaxUint32 to prevent overflow when multiplied
config.commandTimeout = flag.Uint64("t", math.MaxUint32, "timeout for executed command (secs)")
flag.Parse()
reader := bufio.NewReader(os.Stdin)
commands := []string{}
for {
command, _ := reader.ReadString('\n')
// EOF?
if len(command) == 0 {
break
}
commands = append(commands, command)
}
taskID := 0
for i := uint(0); i < *config.repeatCount; i++ {
for _, command := range commands {
command = strings.TrimSpace(command)
if len(command) > 0 {
wg.Add(1)
taskID++
go RunCmd(command, taskID, &wg, getNextColor())
if *config.xargsMode {
wg.Wait()
}
}
}
if !*config.repeatConcurrent || *config.xargsMode {
wg.Wait()
}
}
// everything might be concurrent above so we wait here at the end
wg.Wait()
// when we come here, all commands finish executing, so it is safe to read
// results without a Lock
for _, result := range results {
log.Println(result)
}
log.Println(fmt.Sprintf("Total elapsed: %s", time.Since(startTime)))
}