-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess.go
More file actions
90 lines (83 loc) · 2.48 KB
/
process.go
File metadata and controls
90 lines (83 loc) · 2.48 KB
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 main
import (
"bytes"
"fmt"
"os"
"os/exec"
"strings"
"sync"
"time"
)
var runningCommandsMap = make(map[*exec.Cmd]struct{})
var runningCommandsMutex = sync.Mutex{}
func registerRunningCommand(c *exec.Cmd) {
runningCommandsMutex.Lock()
defer runningCommandsMutex.Unlock()
debugLog("registering running command: %s", strings.Join(c.Args, " "))
runningCommandsMap[c] = struct{}{}
}
func unregisterRunningCommand(c *exec.Cmd) {
runningCommandsMutex.Lock()
defer runningCommandsMutex.Unlock()
debugLog("unregistering running command: %s", strings.Join(c.Args, " "))
delete(runningCommandsMap, c)
}
func broadcastSignalToRunningCommands(sig os.Signal) {
runningCommandsMutex.Lock()
defer runningCommandsMutex.Unlock()
for c := range runningCommandsMap {
if c.Process == nil {
continue
}
p := c.Process
debugLog("sending signal %v to process %d", sig, p.Pid)
err := p.Signal(sig)
if err != nil {
fmt.Printf("failed sending signal %v to process %d: %v\n", sig, p.Pid, err)
}
}
}
// directOutput: if true, command's stdout and stderr are directly connected to os.Stdout and os.Stderr. this is used to run the actual command
// if false, command's stdout and stderr are captured and returned, useful for the exec function used in the templates
func runCommand(cmdParts []string, directOutput bool) (output string, err error) {
debugLog("running command: %s", strings.Join(cmdParts, " "))
startTime := time.Now()
defer func() {
debugLog("command '%s' finished in %s", strings.Join(cmdParts, " "), time.Since(startTime))
}()
var cmd *exec.Cmd
if len(cmdParts) == 1 {
cmd = exec.Command(cmdParts[0])
} else {
cmd = exec.Command(cmdParts[0], cmdParts[1:]...)
}
registerRunningCommand(cmd)
defer unregisterRunningCommand(cmd)
if directOutput {
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
err = cmd.Run()
return
}
stderrBuffer := bytes.NewBuffer(make([]byte, 0))
cmd.Stderr = stderrBuffer
stdoutBuffer := bytes.NewBuffer(make([]byte, 0))
cmd.Stdout = stdoutBuffer
err = cmd.Run()
stderrBytes := stderrBuffer.Bytes()
stdoutBytes := stdoutBuffer.Bytes()
output = string(stdoutBytes)
if err != nil {
err = fmt.Errorf("%w: %s", err, string(stderrBytes))
return
}
if cmd.ProcessState.ExitCode() > 0 {
err = fmt.Errorf("exit code %d: %s", cmd.ProcessState.ExitCode(), string(stderrBytes))
return
}
if len(stderrBytes) > 0 {
debugLog("command '%s' produced stderr output: %s", strings.Join(cmdParts, " "), string(stderrBytes))
}
return
}