-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathexec_cmd_runner_test.go
More file actions
508 lines (441 loc) · 14.7 KB
/
exec_cmd_runner_test.go
File metadata and controls
508 lines (441 loc) · 14.7 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
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
package system_test
import (
"fmt"
"os"
"runtime"
"strings"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
boshlog "github.com/cloudfoundry/bosh-utils/logger"
"github.com/cloudfoundry/bosh-utils/logger/loggerfakes"
. "github.com/cloudfoundry/bosh-utils/system"
fakesys "github.com/cloudfoundry/bosh-utils/system/fakes"
"github.com/hekmon/processpriority"
)
const ErrExitCode = 14
func osSpecificCommand(cmdName string) Command {
if isWindows {
return windowsCommand(cmdName)
}
return unixCommand(cmdName)
}
func windowsCommand(cmdName string) Command {
return map[string]Command{
"pwd": {
Name: "powershell",
Args: []string{"echo $PWD"},
WorkingDir: `C:\windows\temp`,
},
"stderr": {
Name: "powershell",
Args: []string{"[Console]::Error.WriteLine('error-output')"},
},
"exit": {
Name: "powershell",
Args: []string{fmt.Sprintf("exit %d", ErrExitCode)},
},
"ls": {
Name: "powershell",
Args: []string{"dir"},
WorkingDir: ".",
},
"env": {
Name: "cmd.exe",
Args: []string{"/C", "SET"},
Env: map[string]string{
"FOO": "BAR",
},
},
"echo": {
Name: "powershell",
Args: []string{"Write-Host", "Hello World!"},
},
}[cmdName]
}
func unixCommand(cmdName string) Command {
return map[string]Command{
"pwd": {
Name: "bash",
Args: []string{"-c", "echo $PWD"},
WorkingDir: `/tmp`,
},
"stderr": {
Name: "bash",
Args: []string{"-c", "echo error-output >&2"},
},
"exit": {
Name: "bash",
Args: []string{"-c", fmt.Sprintf("exit %d", ErrExitCode)},
},
"ls": {
Name: "ls",
Args: []string{"-l"},
WorkingDir: ".",
},
"env": {
Name: "env",
Env: map[string]string{
"FOO": "BAR",
},
},
"echo": {
Name: "echo",
Args: []string{"Hello World!"},
},
}[cmdName]
}
func parseEnvFields(envDump string, convertKeysToUpper bool) map[string]string {
fields := make(map[string]string)
envDump = strings.ReplaceAll(envDump, "\r", "")
for _, line := range strings.Split(envDump, "\n") {
// don't split on '=' as '=' is allowed in the value on Windows
if n := strings.IndexByte(line, '='); n != -1 {
key := line[:n] // key
val := line[n+1:] // key
if convertKeysToUpper {
fields[strings.ToUpper(key)] = val
} else {
fields[key] = val
}
}
}
return fields
}
var _ = Describe("execCmdRunner", func() {
var (
runner CmdRunner
)
BeforeEach(func() {
runner = NewExecCmdRunner(boshlog.NewLogger(boshlog.LevelNone))
})
Describe("RunComplexCommand", func() {
It("run complex command with working directory", func() {
cmd := osSpecificCommand("ls")
stdout, stderr, status, err := runner.RunComplexCommand(cmd)
Expect(err).ToNot(HaveOccurred())
Expect(stdout).To(ContainSubstring("exec_cmd_runner_fixtures"))
Expect(stderr).To(BeEmpty())
Expect(status).To(Equal(0))
})
It("run complex command with env", func() {
cmd := osSpecificCommand("env")
stdout, stderr, status, err := runner.RunComplexCommand(cmd)
Expect(err).ToNot(HaveOccurred())
envVars := parseEnvFields(stdout, true)
Expect(envVars).To(HaveKeyWithValue("FOO", "BAR"))
Expect(envVars).To(HaveKey("PATH"))
Expect(stderr).To(BeEmpty())
Expect(status).To(Equal(0))
})
It("uses the env vars specified in the Command", func() {
GinkgoT().Setenv("_FOO", "BAR")
cmd := osSpecificCommand("env")
cmd.Env = map[string]string{
"_FOO": "BAZZZ",
}
stdout, _, _, err := runner.RunComplexCommand(cmd)
Expect(err).ToNot(HaveOccurred())
envVars := parseEnvFields(stdout, false)
Expect(envVars).To(HaveKeyWithValue("_FOO", "BAZZZ"))
})
Context("unix specific behavior", func() {
BeforeEach(func() {
if isWindows {
Skip("unix only test")
}
})
It("performs a case-sensitive comparison of env vars when on *Nix", func() {
GinkgoT().Setenv("_FOO", "BAR")
cmd := osSpecificCommand("env")
cmd.Env = map[string]string{
"_foo": "BAZZZ",
"ABC": "XYZ",
"abc": "xyz",
}
stdout, _, _, err := runner.RunComplexCommand(cmd)
Expect(err).ToNot(HaveOccurred())
envVars := parseEnvFields(stdout, false)
Expect(envVars).To(HaveKeyWithValue("_FOO", "BAR"))
Expect(envVars).To(HaveKeyWithValue("_foo", "BAZZZ"))
Expect(err).ToNot(HaveOccurred())
Expect(envVars).To(HaveKeyWithValue("ABC", "XYZ"))
Expect(envVars).To(HaveKeyWithValue("abc", "xyz"))
})
It("runs a command nicer than itself", func() {
// Write script that echos the its nice value
script := "#!/bin/bash\nnice\n"
tmpFile, err := os.CreateTemp("", "tmp-script-*.sh")
Expect(err).ToNot(HaveOccurred())
defer os.Remove(tmpFile.Name())
_, err = tmpFile.WriteString(script)
Expect(err).ToNot(HaveOccurred())
err = tmpFile.Close()
Expect(err).ToNot(HaveOccurred())
err = os.Chmod(tmpFile.Name(), 0700)
Expect(err).ToNot(HaveOccurred())
parentPid := os.Getpid()
_, rawParentPrio, err := processpriority.Get(parentPid)
Expect(err).ToNot(HaveOccurred())
expectedOutput := fmt.Sprintf("%d\n", rawParentPrio+5)
// Run script with SpawnWithLowerPriority
cmd := Command{
Name: tmpFile.Name(),
SpawnWithLowerPriority: true,
}
stdout, _, _, err := runner.RunComplexCommand(cmd)
Expect(err).ToNot(HaveOccurred())
Expect(stdout).To(Equal(expectedOutput))
})
})
Context("windows specific behavior", func() {
BeforeEach(func() {
if !isWindows {
Skip("Windows only test")
}
})
setupWindowsEnvTest := func(cmdVars map[string]string) (map[string]string, error) {
os.Setenv("_FOO", "BAR") //nolint:errcheck
defer os.Unsetenv("_FOO")
cmd := osSpecificCommand("env")
cmd.Env = cmdVars
stdout, _, _, err := runner.RunComplexCommand(cmd)
if err != nil {
return nil, err
}
// don't upper case key names we want to assert that the lower case
// duplicates provided in Command.Env are used. also, Windows does
// not care about key case.
envVars := parseEnvFields(stdout, false)
return envVars, nil
}
It("uses the env vars specified in the Command", func() {
envVars, err := setupWindowsEnvTest(map[string]string{
"_FOO": "BAZZZ",
})
Expect(err).ToNot(HaveOccurred())
Expect(envVars).To(HaveKeyWithValue("_FOO", "BAZZZ"))
})
It("env var comparison is case-insensitive on Windows", func() {
envVars, err := setupWindowsEnvTest(map[string]string{
"_foo": "BAZZZ",
})
Expect(err).ToNot(HaveOccurred())
Expect(envVars).ToNot(HaveKey("_FOO"))
Expect(envVars).To(HaveKeyWithValue("_foo", "BAZZZ"))
})
It("deterministically handles duplicate env vars on Windows", func() {
envVars, err := setupWindowsEnvTest(map[string]string{
"_foo": "BAZZZ",
"_bar": "alpha=second",
"_BAR": "alpha=first",
})
Expect(err).ToNot(HaveOccurred())
// vars in Command.Env replace System vars with the same name,
// compared case-insensitively. Therefore, the lower case '_foo'
// replaces the upper case '_FOO'.
//
Expect(envVars).ToNot(HaveKey("_FOO"))
Expect(envVars).To(HaveKeyWithValue("_foo", "BAZZZ"))
// Duplicate env vars in Command.Env are de-duped before being
// merged with the System env vars. Since the Command.Env is
// a map we sort the keys alphabetically before de-duping so
// that the result is deterministic.
//
Expect(envVars).ToNot(HaveKey("_bar"))
Expect(envVars).To(HaveKeyWithValue("_BAR", "alpha=first"))
})
It("runs a command nicer than itself", func() {
// Write script that echos the its nice value
script := "$proc = Get-Process -Id $PID\nWrite-Output $proc.PriorityClass"
tmpFile, err := os.CreateTemp("", "tmp-script-*.ps1")
Expect(err).ToNot(HaveOccurred())
defer os.Remove(tmpFile.Name())
_, err = tmpFile.WriteString(script)
Expect(err).ToNot(HaveOccurred())
err = tmpFile.Close()
Expect(err).ToNot(HaveOccurred())
err = os.Chmod(tmpFile.Name(), 0700)
Expect(err).ToNot(HaveOccurred())
// Run script with SpawnWithLowerPriority
cmd := Command{
Name: "powershell",
Args: []string{"-ExecutionPolicy", "Bypass", "-File", tmpFile.Name()},
SpawnWithLowerPriority: true,
}
stdout, _, _, err := runner.RunComplexCommand(cmd)
Expect(err).ToNot(HaveOccurred())
Expect(stdout).To(Equal("Idle\r\n"))
})
})
It("run complex command with stdin", func() {
input := "This is STDIN\nWith another line."
cmd := Command{
Name: catPath,
Stdin: strings.NewReader(input),
}
stdout, stderr, status, err := runner.RunComplexCommand(cmd)
Expect(err).ToNot(HaveOccurred())
Expect(stdout).To(Equal(input))
Expect(stderr).To(BeEmpty())
Expect(status).To(Equal(0))
})
It("prints stdout/stderr to provided I/O object", func() {
fs := fakesys.NewFakeFileSystem()
stdoutFile, err := fs.OpenFile("/fake-stdout-path", os.O_RDWR, os.FileMode(0644))
Expect(err).ToNot(HaveOccurred())
stderrFile, err := fs.OpenFile("/fake-stderr-path", os.O_RDWR, os.FileMode(0644))
Expect(err).ToNot(HaveOccurred())
cmd := Command{
Name: catPath,
Args: []string{"-stdout", "fake-out", "-stderr", "fake-err"},
Stdout: stdoutFile,
Stderr: stderrFile,
}
stdout, stderr, status, err := runner.RunComplexCommand(cmd)
Expect(err).ToNot(HaveOccurred())
Expect(stdout).To(BeEmpty())
Expect(stderr).To(BeEmpty())
Expect(status).To(Equal(0))
stdoutContents := make([]byte, 1024)
_, err = stdoutFile.Read(stdoutContents)
Expect(err).ToNot(HaveOccurred())
Expect(string(stdoutContents)).To(ContainSubstring("fake-out"))
stderrContents := make([]byte, 1024)
_, err = stderrFile.Read(stderrContents)
Expect(err).ToNot(HaveOccurred())
Expect(string(stderrContents)).To(ContainSubstring("fake-err"))
})
})
Describe("RunComplexCommandAsync", func() {
It("populates stdout and stderr", func() {
cmd := osSpecificCommand("ls")
process, err := runner.RunComplexCommandAsync(cmd)
Expect(err).ToNot(HaveOccurred())
result := <-process.Wait()
Expect(result.Error).ToNot(HaveOccurred())
Expect(result.ExitStatus).To(Equal(0))
})
It("populates stdout and stderr", func() {
cmd := Command{
Name: catPath,
Args: []string{"-stdout", "STDOUT", "-stderr", "STDERR"},
}
process, err := runner.RunComplexCommandAsync(cmd)
Expect(err).ToNot(HaveOccurred())
result := <-process.Wait()
Expect(result.Error).ToNot(HaveOccurred())
Expect(result.Stdout).To(Equal("STDOUT\n"))
Expect(result.Stderr).To(Equal("STDERR\n"))
})
It("returns error and sets status to exit status of command if it exits with non-0 status", func() {
cmd := osSpecificCommand("exit")
process, err := runner.RunComplexCommandAsync(cmd)
Expect(err).ToNot(HaveOccurred())
result := <-process.Wait()
Expect(result.Error).To(HaveOccurred())
Expect(result.ExitStatus).To(Equal(ErrExitCode))
})
It("allows setting custom env variable in addition to inheriting process env variables", func() {
cmd := osSpecificCommand("env")
process, err := runner.RunComplexCommandAsync(cmd)
Expect(err).ToNot(HaveOccurred())
result := <-process.Wait()
Expect(result.Error).ToNot(HaveOccurred())
Expect(result.Stdout).To(ContainSubstring("FOO=BAR"))
Expect(result.Stdout).To(ContainSubstring("PATH="))
})
It("changes working dir", func() {
cmd := osSpecificCommand("pwd")
process, err := runner.RunComplexCommandAsync(cmd)
Expect(err).ToNot(HaveOccurred())
result := <-process.Wait()
Expect(result.Error).ToNot(HaveOccurred())
Expect(result.Stdout).To(ContainSubstring(cmd.WorkingDir))
})
})
Describe("RunCommand", func() {
It("run command", func() {
cmd := osSpecificCommand("echo")
stdout, stderr, status, err := runner.RunCommand(cmd.Name, cmd.Args...)
Expect(err).ToNot(HaveOccurred())
Expect(stdout).To(Equal("Hello World!\n"))
Expect(stderr).To(BeEmpty())
Expect(status).To(Equal(0))
})
It("run command with error output", func() {
cmd := osSpecificCommand("stderr")
stdout, stderr, status, err := runner.RunCommand(cmd.Name, cmd.Args...)
Expect(err).ToNot(HaveOccurred())
Expect(stdout).To(BeEmpty())
Expect(stderr).To(ContainSubstring("error-output"))
Expect(status).To(Equal(0))
})
It("run command with non-0 exit status", func() {
cmd := osSpecificCommand("exit")
stdout, stderr, status, err := runner.RunCommand(cmd.Name, cmd.Args...)
Expect(err).To(HaveOccurred())
Expect(stdout).To(BeEmpty())
Expect(stderr).To(BeEmpty())
Expect(status).To(Equal(ErrExitCode))
})
It("run command with error", func() {
stdout, stderr, status, err := runner.RunCommand(falsePath)
Expect(err).To(HaveOccurred())
Expect(stderr).To(BeEmpty())
Expect(stdout).To(BeEmpty())
Expect(status).To(Equal(1))
})
It("run command with error with args", func() {
stdout, stderr, status, err := runner.RunCommand(falsePath, "second arg")
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Equal(fmt.Sprintf("Running command: '%s second arg', stdout: '', stderr: '': exit status 1", falsePath)))
Expect(stderr).To(BeEmpty())
Expect(stdout).To(BeEmpty())
Expect(status).To(Equal(1))
})
It("run command with cmd not found", func() {
stdout, stderr, status, err := runner.RunCommand("something that does not exist")
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(Or(ContainSubstring("not found"), ContainSubstring("ObjectNotFound")))
if runtime.GOOS != "windows" {
Expect(stderr).To(BeEmpty())
}
Expect(stdout).To(BeEmpty())
Expect(status).ToNot(Equal(0))
})
})
Describe("RunCommandWithInput", func() {
It("run command with input", func() {
stdout, stderr, status, err := runner.RunCommandWithInput("foo\nbar\nbaz", catPath)
Expect(err).ToNot(HaveOccurred())
Expect(stdout).To(Equal("foo\nbar\nbaz"))
Expect(stderr).To(BeEmpty())
Expect(status).To(Equal(0))
})
})
Describe("RunCommandQuietly", func() {
It("run command with input", func() {
logger := &loggerfakes.FakeLogger{}
runner = NewExecCmdRunner(logger)
cmd := osSpecificCommand("echo")
stdout, stderr, status, err := runner.RunCommandQuietly(cmd.Name, cmd.Args...)
Expect(err).ToNot(HaveOccurred())
Expect(logger.DebugCallCount()).To(Equal(2))
Expect(stdout).To(Equal("Hello World!\n"))
Expect(stderr).To(BeEmpty())
Expect(status).To(Equal(0))
})
})
Describe("CommandExists", func() {
It("command exists", func() {
var cmd string
if runtime.GOOS == "windows" {
cmd = "cmd.exe"
} else {
cmd = "env"
}
Expect(runner.CommandExists(cmd)).To(BeTrue())
Expect(runner.CommandExists("absolutely-does-not-exist-ever-please-unicorns")).To(BeFalse())
})
})
})