This repository has been archived by the owner on Nov 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun.go
127 lines (109 loc) · 2.96 KB
/
run.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
package main
import (
"log"
"io"
"syscall"
"os/exec"
"bufio"
"strings"
"time"
"os"
)
func run(api *Api, workflowFile string) {
if *executionPeriod == 0 {
status := executeWorkflowScript(api, workflowFile)
os.Exit(status)
return
}
running := false
execute := func() {
if (running) {
return
}
defer func() {
running = false
}()
running = true
executeWorkflowScript(api, workflowFile)
}
go execute()
ticker := time.NewTicker(time.Duration(*executionPeriod) * time.Second)
quit := make(chan struct{})
for {
select {
case <-ticker.C:
go execute()
case <-quit:
ticker.Stop()
return
}
}
}
func executeWorkflowScript(api *Api, workflowFile string) int {
log.Println("Executing workflow by Node.js.")
exe := api.CreateExecution()
cmd := exec.Command("node", workflowFile)
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Fatal(err)
}
stderr, err := cmd.StderrPipe()
if err != nil {
log.Fatal(err)
}
err = cmd.Start()
if err != nil {
log.Fatal(err)
}
go processOutput(api, exe, stdout, false)
go processOutput(api, exe, stderr, true)
finished := func(err error) int {
exitStatusCode := 0
if err != nil {
log.Println("Error during execution of the workflow script.")
if exitError, ok := err.(*exec.ExitError); ok {
if status, ok := exitError.Sys().(syscall.WaitStatus); ok {
exitStatusCode = status.ExitStatus()
}
}
}
api.FinalizeExecution(exe, exitStatusCode)
log.Println("Workflow execution took :", exe.Finish.Sub(exe.Start))
log.Println("Workflow exit status code:", exe.Status)
return exe.Status
}
if *executionTimeout == 0 {
return finished(cmd.Wait())
}
done := make(chan error, 1)
go func() {
done <- cmd.Wait()
}()
select {
case <-time.After(time.Duration(*executionTimeout) * time.Second):
if err := cmd.Process.Kill(); err != nil {
log.Println("ERROR - failed to kill the workflow process:", err)
}
log.Println("Workflow process is killed as timeout reached.")
return 1
case err := <-done:
return finished(err)
}
}
func processOutput(api *Api, exe *Execution, rd io.Reader, error bool) {
reader := bufio.NewReader(rd)
for {
input, err := reader.ReadString('\n')
if err != nil || err == io.EOF {
break
}
workflowLog := strings.TrimSuffix(input, "\n")
api.ExecutionLog(exe, workflowLog, error)
message := "WORKFLOW - " + workflowLog
if error {
log.Println("ERROR - ", message);
} else {
log.Println(message);
}
}
}