-
Notifications
You must be signed in to change notification settings - Fork 51
/
remote_execution_runner.go
105 lines (82 loc) · 2.04 KB
/
remote_execution_runner.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
package main
import (
"fmt"
"strings"
"github.com/mattn/go-shellwords"
"github.com/reconquest/hierr-go"
)
var sudoCommand = []string{"sudo", "-n", "-E", "-H"}
type remoteExecutionRunner struct {
command []string
args []string
shell string
directory string
sudo bool
serial bool
term bool
}
func (runner *remoteExecutionRunner) run(
cluster *distributedLock,
setupCallback func(*remoteExecutionNode),
) (*remoteExecution, error) {
commandline := joinCommand(runner.command)
if runner.directory != "" {
commandline = fmt.Sprintf("cd %s && { %s; }",
escapeCommandArgumentStrict(runner.directory),
commandline,
)
}
if len(runner.shell) != 0 {
commandline = wrapCommandIntoShell(
commandline,
runner.shell,
runner.args,
)
}
if runner.sudo {
commandline = joinCommand(sudoCommand) + " " + commandline
}
command, err := shellwords.Parse(commandline)
if err != nil {
return nil, hierr.Errorf(
err, "unparsable command line: %s", commandline,
)
}
return runRemoteExecution(cluster, command, setupCallback, runner.serial, runner.term)
}
func wrapCommandIntoShell(command, shell string, args []string) string {
if shell == "" {
return command
}
command = strings.Replace(shell, `{}`, command, -1)
if len(args) == 0 {
return command
}
escapedArgs := []string{}
for _, arg := range args {
escapedArgs = append(escapedArgs, escapeCommandArgumentStrict(arg))
}
return command + " _ " + strings.Join(escapedArgs, " ")
}
func joinCommand(command []string) string {
escapedParts := []string{}
for _, part := range command {
escapedParts = append(escapedParts, escapeCommandArgument(part))
}
return strings.Join(escapedParts, ` `)
}
func escapeCommandArgument(argument string) string {
argument = strings.Replace(argument, `'`, `'\''`, -1)
return argument
}
func escapeCommandArgumentStrict(argument string) string {
escaper := strings.NewReplacer(
`\`, `\\`,
"`", "\\`",
`"`, `\"`,
`'`, `'\''`,
`$`, `\$`,
)
escaper.Replace(argument)
return `"` + argument + `"`
}