-
Notifications
You must be signed in to change notification settings - Fork 67
/
commands.go
333 lines (276 loc) · 6.42 KB
/
commands.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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
// Copyright 2015-2023 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
// Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain
// rights in this software.
package main
import (
"bufio"
"bytes"
"fmt"
"net"
"net/url"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/sandia-minimega/minimega/v2/internal/ron"
log "github.com/sandia-minimega/minimega/v2/pkg/minilog"
)
func processCommand(cmd *ron.Command) {
log.Debug("processCommand %v", cmd)
resp := &ron.Response{
ID: cmd.ID,
}
// get any files needed for the command
if len(cmd.FilesSend) != 0 {
recvFiles(cmd.FilesSend)
}
// kill processes before starting new ones
if cmd.PID != 0 {
kill(cmd.PID)
}
if cmd.KillAll != "" {
killAll(cmd.KillAll)
}
// adjust the log level, if a new level is provided
if cmd.Level != nil {
log.Info("setting level to: %v", *cmd.Level)
log.SetLevelAll(*cmd.Level)
}
if len(cmd.Command) != 0 {
resp.Stdout, resp.Stderr, resp.ExitCode = runCommand(cmd.Stdin, cmd.Stdout, cmd.Stderr, cmd.Command, cmd.Background)
// don't record exit code if this is a background command
resp.RecordExitCode = !cmd.Background
}
if cmd.ConnTest != nil {
resp.Stdout, resp.Stderr = testConnect(cmd.ConnTest)
}
if len(cmd.FilesRecv) != 0 {
sendFiles(cmd.ID, cmd.FilesRecv)
}
appendResponse(resp)
}
// lookPath wraps exec.LookPath to check $PATH and the files path
func lookPath(file string) (string, error) {
path, err := exec.LookPath(file)
if err == nil {
return path, nil
}
// file contains a slash, shouldn't search files path
if strings.Contains(file, "/") {
return "", &exec.Error{Name: file, Err: exec.ErrNotFound}
}
file = filepath.Join(*f_path, "files", file)
return exec.LookPath(file)
}
func runCommand(stdin, stdout, stderr string, command []string, background bool) (string, string, int) {
done := make(chan struct{})
var bufout, buferr bytes.Buffer
path, err := lookPath(command[0])
if err != nil {
log.Errorln(err)
close(done)
return "", err.Error(), -1
}
cmd := &exec.Cmd{
Path: path,
Args: command,
}
if stdin != "" {
pStdin, err := cmd.StdinPipe()
if err != nil {
log.Errorln(err)
return "", "", -1
}
cStdin, err := NewPlumberReader(stdin)
if err != nil {
log.Errorln(err)
return "", "", -1
}
go func() {
<-done
cStdin.Close()
}()
go func() {
for v := range cStdin.C {
_, err := pStdin.Write([]byte(v))
if err != nil {
log.Errorln(err)
return
}
}
pStdin.Close()
}()
}
if stdout != "" {
pStdout, err := cmd.StdoutPipe()
if err != nil {
log.Errorln(err)
close(done)
return "", "", -1
}
cStdout, err := NewPlumberWriter(stdout)
if err != nil {
log.Errorln(err)
close(done)
return "", "", -1
}
go func() {
defer close(cStdout)
scanner := bufio.NewScanner(pStdout)
for scanner.Scan() {
select {
case cStdout <- scanner.Text() + "\n":
case <-done:
return
}
}
if err := scanner.Err(); err != nil {
log.Errorln(err)
return
}
}()
} else {
cmd.Stdout = &bufout
}
if stderr != "" {
pStderr, err := cmd.StderrPipe()
if err != nil {
log.Errorln(err)
close(done)
return "", "", -1
}
cStderr, err := NewPlumberWriter(stderr)
if err != nil {
log.Errorln(err)
close(done)
return "", "", -1
}
go func() {
defer close(cStderr)
scanner := bufio.NewScanner(pStderr)
for scanner.Scan() {
select {
case cStderr <- scanner.Text() + "\n":
case <-done:
return
}
}
if err := scanner.Err(); err != nil {
log.Errorln(err)
return
}
}()
} else {
cmd.Stderr = &buferr
}
log.Info("executing: %v", command)
if background {
log.Debug("starting in background")
if err := cmd.Start(); err != nil {
log.Errorln(err)
return "", buferr.String(), -1
}
pid := cmd.Process.Pid
client.Lock()
defer client.Unlock()
client.Processes[pid] = &Process{
PID: pid,
Command: command,
process: cmd.Process,
}
go func() {
cmd.Wait()
log.Info("command exited: %v", command)
if bufout.Len() > 0 {
log.Info(bufout.String())
}
if buferr.Len() > 0 {
log.Info(buferr.String())
}
client.Lock()
defer client.Unlock()
delete(client.Processes, pid)
}()
return "", "", 0
}
// To avoid returning a false positive, default to -1 in case error below
// isn't an exec.ExitError.
exitCode := -1
if err := cmd.Run(); err == nil {
exitCode = 0
} else {
log.Errorln(err)
if exitErr, ok := err.(*exec.ExitError); ok {
exitCode = exitErr.ExitCode()
}
}
return bufout.String(), buferr.String(), exitCode
}
func kill(pid int) {
client.Lock()
defer client.Unlock()
if pid == -1 {
// Wildcard
log.Info("killing all processes")
for _, p := range client.Processes {
if err := p.process.Kill(); err != nil {
log.Errorln(err)
}
}
return
}
log.Info("killing PID %v", pid)
if p, ok := client.Processes[pid]; ok {
if err := p.process.Kill(); err != nil {
log.Errorln(err)
}
return
}
log.Error("no such process: %v", pid)
}
func killAll(needle string) {
client.Lock()
defer client.Unlock()
log.Info("killing all processes matching `%v`", needle)
for _, p := range client.Processes {
if strings.Contains(strings.Join(p.Command, " "), needle) {
log.Info("killing matched process: %v", p.Command)
if err := p.process.Kill(); err != nil {
log.Errorln(err)
}
}
}
}
func testConnect(test *ron.ConnTest) (string, string) {
log.Debug("testConnect called with %v", *test)
uri, err := url.Parse(test.Endpoint)
if err != nil {
return "", fmt.Sprintf("unable to parse test URI %s: %v", test.Endpoint, err)
}
timeout := time.After(test.Wait)
for {
select {
case <-timeout:
return fmt.Sprintf("%s | fail", uri.Host), ""
default:
if conn, err := net.DialTimeout(uri.Scheme, uri.Host, 500*time.Millisecond); err == nil {
defer conn.Close()
if uri.Scheme == "udp" {
if err := conn.SetDeadline(time.Now().Add(500 * time.Millisecond)); err != nil {
return fmt.Sprintf("%s | fail", uri.Host), ""
}
if len(test.Packet) > 0 {
if _, err := conn.Write(test.Packet); err != nil {
return fmt.Sprintf("%s | fail", uri.Host), ""
}
}
buf := make([]byte, 1)
if _, err := conn.Read(buf); err != nil {
return fmt.Sprintf("%s | fail", uri.Host), ""
}
}
return fmt.Sprintf("%s | pass", uri.Host), ""
}
}
}
}