-
Notifications
You must be signed in to change notification settings - Fork 0
/
command.go
198 lines (163 loc) · 4.43 KB
/
command.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
package nodes
import (
"errors"
"fmt"
"io"
"log/slog"
"os"
"os/exec"
"strings"
"sync"
"github.com/ntnn/tensile"
)
var _ tensile.Node = (*Command)(nil)
// Command executes command lines.
type Command struct {
// Description is used as the nodes identifier.
Description string
// The binary to run.
// Defaults to 'bash'.
Binary string
// Arguments to pass when invoking the binary.
// Each argument is templated.
// Defaults to ["{{.Custom.script}}"] if .Script is not empty, [] otherwise.
Arguments []string
// A script to template and pass to .Binary.
Script string
// Input is passed to the process as stdin line by line.
// Each line is templated.
//
// Useful when executing a binary that expects input (e.g. a password for authenticating).
Input []string
}
func (sh Command) Shape() tensile.Shape {
return tensile.Noop
}
func (sh Command) Identifier() string {
return sh.Description
}
func (sh *Command) Validate() error {
if sh.Binary == "" {
sh.Binary = "bash"
}
if len(sh.Arguments) == 0 && len(sh.Script) > 0 {
sh.Arguments = []string{
"{{.Custom.script}}",
}
}
return nil
}
type CommandOutput struct {
Result int
Stdout, Stderr string
}
func (sh Command) Execute(ctx tensile.Context) (any, error) {
templateCustom := map[string]any{}
// template script
if len(sh.Script) > 0 {
f, err := os.CreateTemp("", "tensile-*")
if err != nil {
return nil, fmt.Errorf("nodes: error creating temporary file: %w", err)
}
defer os.Remove(f.Name())
defer f.Close()
if err := tensile.Template(ctx.Facts(), sh.Script, f, templateCustom); err != nil {
return nil, fmt.Errorf("nodes: error templating script to temporary file: %w", err)
}
templateCustom["script"] = f.Name()
}
// create exec.Command
binPath, err := exec.LookPath(sh.Binary)
if err != nil {
return nil, fmt.Errorf("nodes: unable to find path for %q: %w", sh.Binary, err)
}
arguments := make([]string, len(sh.Arguments))
for i, arg := range sh.Arguments {
s, err := tensile.TemplateString(ctx.Facts(), arg, templateCustom)
if err != nil {
return nil, fmt.Errorf("nodes: error templating argument %d %q: %w", i, arg, err)
}
arguments[i] = s
}
ctx.Logger().Debug("command line",
slog.String("binary", sh.Binary),
slog.String("binpath", binPath),
slog.Any("raw arguments", sh.Arguments),
slog.Any("arguments", arguments),
)
cmd := exec.CommandContext(ctx.Context(), binPath, arguments...)
wg := &sync.WaitGroup{}
if len(sh.Input) > 0 {
wg.Add(1)
stdinPipe, err := cmd.StdinPipe()
if err != nil {
return nil, fmt.Errorf("nodes: error getting stdin pipe: %w", err)
}
go func() {
defer stdinPipe.Close()
defer wg.Done()
for _, line := range sh.Input {
if _, err := stdinPipe.Write([]byte(line + "\n")); err != nil {
// TODO
}
}
}()
}
// TODO support combined output as well
stdout := &strings.Builder{}
stdoutPipe, err := cmd.StdoutPipe()
if err != nil {
return nil, fmt.Errorf("nodes: error getting stdout pipe: %w", err)
}
wg.Add(1)
go func() {
defer wg.Done()
if _, err := io.Copy(stdout, stdoutPipe); err != nil {
// TODO
}
ctx.Logger().Debug("stdout", slog.String("lines", stdout.String()))
}()
stderr := &strings.Builder{}
stderrPipe, err := cmd.StderrPipe()
if err != nil {
return nil, fmt.Errorf("nodes: error getting stderr pipe: %w", err)
}
wg.Add(1)
go func() {
defer wg.Done()
if _, err := io.Copy(stderr, stderrPipe); err != nil {
// TODO
}
ctx.Logger().Debug("stderr", slog.String("lines", stderr.String()))
}()
makeOutput := func(msg string, err error) (*CommandOutput, error) {
wg.Wait()
out := &CommandOutput{
Result: cmd.ProcessState.ExitCode(),
Stdout: stdout.String(),
Stderr: stderr.String(),
}
if err == nil {
return out, nil
}
var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
out.Result = exitErr.ExitCode()
if out.Result < 0 || out.Result >= 126 {
// exit codes lower than zero are kernel errors
// exit codes higher/equal 126 are generic errors
return out, fmt.Errorf("nodes: %s: %w", msg, exitErr)
}
}
// if the error is not exec.ExitError a larger issue is likely present
return out, fmt.Errorf("nodes: %s: %w", msg, err)
}
// execute
if err := cmd.Start(); err != nil {
return makeOutput("error starting process", err)
}
if err := cmd.Wait(); err != nil {
return makeOutput("error waiting on process", err)
}
return makeOutput("process finished", err)
}