/
run_cmd.go
85 lines (64 loc) · 1.91 KB
/
run_cmd.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
package pkg
import (
"fmt"
"os"
"strings"
"github.com/go-cmd/cmd"
)
// RunCMD execute long running script with disabling output buffering, and enabling streaming.
// return the exit code of the script process.
func RunCMD(scriptName string) int {
cmdOptions := cmd.Options{
Buffered: false,
Streaming: true,
}
// Create Cmd with options
envCmd := cmd.NewCmdOptions(cmdOptions, "/bin/sh", scriptName)
// cmdDone will be set to true whenever the "E2E CANARY TEST - DONE" line is outputted, meaning the script is done
// This is to work around the exit code returns -1 even though the script is done correctly
cmdDone := false
// Print STDOUT and STDERR lines streaming from Cmd
doneChan := make(chan struct{})
go func() {
defer func() {
close(doneChan)
}()
// Done when both channels have been closed
for envCmd.Stdout != nil || envCmd.Stderr != nil {
select {
case line, open := <-envCmd.Stdout:
if !open {
envCmd.Stdout = nil
continue
}
fmt.Println(line)
if strings.Contains(line, "E2E CANARY TEST -") {
if strings.Contains(line, "E2E CANARY TEST - DONE") {
cmdDone = true
}
// For some reason, the Stdout and Stderr channels are not closed even after the script is done.
// Workaround: echo "E2E CANARY TEST - ***" as the last line of the script.
// Stop the cmd when standard output contains such keywords
envCmd.Stop()
continue
}
case line, open := <-envCmd.Stderr:
if !open {
envCmd.Stderr = nil
continue
}
fmt.Fprintln(os.Stderr, line)
}
}
}()
// start the command asynchronously
statusChan := envCmd.Start()
// Wait for goroutine to print everything
<-doneChan
finalStatus := <-statusChan
fmt.Println("Script: ", scriptName, ", Runtime: ", finalStatus.Runtime, " Seconds", ", ExitCode: ", finalStatus.Exit, ", cmdDone: ", cmdDone)
if cmdDone {
return 0
}
return finalStatus.Exit
}