-
Notifications
You must be signed in to change notification settings - Fork 2k
/
exec_testing.go
354 lines (300 loc) · 8.68 KB
/
exec_testing.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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
package testutils
import (
"context"
"fmt"
"io"
"io/ioutil"
"os"
"reflect"
"regexp"
"runtime"
"strings"
"sync"
"testing"
"time"
"github.com/hashicorp/nomad/plugins/drivers"
dproto "github.com/hashicorp/nomad/plugins/drivers/proto"
"github.com/stretchr/testify/require"
)
func ExecTaskStreamingConformanceTests(t *testing.T, driver *DriverHarness, taskID string) {
t.Helper()
if runtime.GOOS == "windows" {
// tests assume unix-ism now
t.Skip("test assume unix tasks")
}
TestExecTaskStreamingBasicResponses(t, driver, taskID)
TestExecFSIsolation(t, driver, taskID)
}
var ExecTaskStreamingBasicCases = []struct {
Name string
Command string
Tty bool
Stdin string
Stdout interface{}
Stderr interface{}
ExitCode int
}{
{
Name: "notty: basic",
Command: "echo hello stdout; echo hello stderr >&2; exit 43",
Tty: false,
Stdout: "hello stdout\n",
Stderr: "hello stderr\n",
ExitCode: 43,
},
{
Name: "notty: streaming",
Command: "for n in 1 2 3; do echo $n; sleep 1; done",
Tty: false,
Stdout: "1\n2\n3\n",
ExitCode: 0,
},
{
Name: "notty: stty check",
Command: "stty size",
Tty: false,
Stderr: regexp.MustCompile("stty: .?standard input.?: Inappropriate ioctl for device\n"),
ExitCode: 1,
},
{
Name: "notty: stdin passing",
Command: "echo hello from command; head -n1",
Tty: false,
Stdin: "hello from stdin\n",
Stdout: "hello from command\nhello from stdin\n",
ExitCode: 0,
},
{
Name: "notty: children processes",
Command: "(( sleep 3; echo from background ) & ); echo from main; exec sleep 1",
Tty: false,
// when not using tty; wait for all processes to exit matching behavior of `docker exec`
Stdout: "from main\nfrom background\n",
ExitCode: 0,
},
// TTY cases - difference is new lines add `\r` and child process waiting is different
{
Name: "tty: basic",
Command: "echo hello stdout; echo hello stderr >&2; exit 43",
Tty: true,
Stdout: "hello stdout\r\nhello stderr\r\n",
ExitCode: 43,
},
{
Name: "tty: streaming",
Command: "for n in 1 2 3; do echo $n; sleep 1; done",
Tty: true,
Stdout: "1\r\n2\r\n3\r\n",
ExitCode: 0,
},
{
Name: "tty: stty check",
Command: "sleep 1; stty size",
Tty: true,
Stdout: "100 100\r\n",
ExitCode: 0,
},
{
Name: "tty: stdin passing",
Command: "head -n1",
Tty: true,
Stdin: "hello from stdin\n",
// in tty mode, we emit line twice: once for tty echoing and one for the actual head output
Stdout: "hello from stdin\r\nhello from stdin\r\n",
ExitCode: 0,
},
{
Name: "tty: children processes",
Command: "(( sleep 3; echo from background ) & ); echo from main; exec sleep 1",
Tty: true,
// when using tty; wait for lead process only, like `docker exec -it`
Stdout: "from main\r\n",
ExitCode: 0,
},
}
func TestExecTaskStreamingBasicResponses(t *testing.T, driver *DriverHarness, taskID string) {
for _, c := range ExecTaskStreamingBasicCases {
t.Run("basic: "+c.Name, func(t *testing.T) {
result := execTask(t, driver, taskID, c.Command, c.Tty, c.Stdin)
require.Equal(t, c.ExitCode, result.exitCode)
switch s := c.Stdout.(type) {
case string:
require.Equal(t, s, result.stdout)
case *regexp.Regexp:
require.Regexp(t, s, result.stdout)
case nil:
require.Empty(t, result.stdout)
default:
require.Fail(t, "unexpected stdout type", "found %v (%v), but expected string or regexp", s, reflect.TypeOf(s))
}
switch s := c.Stderr.(type) {
case string:
require.Equal(t, s, result.stderr)
case *regexp.Regexp:
require.Regexp(t, s, result.stderr)
case nil:
require.Empty(t, result.stderr)
default:
require.Fail(t, "unexpected stderr type", "found %v (%v), but expected string or regexp", s, reflect.TypeOf(s))
}
})
}
}
// TestExecFSIsolation asserts that exec occurs inside chroot/isolation environment rather than
// on host
func TestExecFSIsolation(t *testing.T, driver *DriverHarness, taskID string) {
t.Run("isolation", func(t *testing.T) {
caps, err := driver.Capabilities()
require.NoError(t, err)
isolated := (caps.FSIsolation != drivers.FSIsolationNone)
text := "hello from the other side"
// write to a file and check it presence in host
w := execTask(t, driver, taskID,
fmt.Sprintf(`FILE=$(mktemp); echo "$FILE"; echo %q >> "${FILE}"`, text),
false, "")
require.Zero(t, w.exitCode)
tempfile := strings.TrimSpace(w.stdout)
if !isolated {
defer os.Remove(tempfile)
}
t.Logf("created file in task: %v", tempfile)
// read from host
b, err := ioutil.ReadFile(tempfile)
if !isolated {
require.NoError(t, err)
require.Equal(t, text, strings.TrimSpace(string(b)))
} else {
require.Error(t, err)
require.True(t, os.IsNotExist(err))
}
// read should succeed from task again
r := execTask(t, driver, taskID,
fmt.Sprintf("cat %q", tempfile),
false, "")
require.Zero(t, r.exitCode)
require.Equal(t, text, strings.TrimSpace(r.stdout))
// we always run in a cgroup - testing freezer cgroup
r = execTask(t, driver, taskID,
fmt.Sprintf("cat /proc/self/cgroup"),
false, "")
require.Zero(t, r.exitCode)
if !strings.Contains(r.stdout, ":freezer:/nomad") && !strings.Contains(r.stdout, "freezer:/docker") {
require.Fail(t, "unexpected freezer cgroup", "expected freezer to be /nomad/ or /docker/, but found:\n%s", r.stdout)
}
})
}
func execTask(t *testing.T, driver *DriverHarness, taskID string, cmd string, tty bool, stdin string) execResult {
stream := newTestExecStream(t, tty, stdin)
ctx, cancelFn := context.WithTimeout(context.Background(), 30*time.Second)
defer cancelFn()
command := []string{"/bin/sh", "-c", cmd}
isRaw := false
exitCode := -2
if raw, ok := driver.impl.(drivers.ExecTaskStreamingRawDriver); ok {
isRaw = true
err := raw.ExecTaskStreamingRaw(ctx, taskID,
command, tty, stream)
require.NoError(t, err)
} else if d, ok := driver.impl.(drivers.ExecTaskStreamingDriver); ok {
execOpts, errCh := drivers.StreamToExecOptions(ctx, command, tty, stream)
r, err := d.ExecTaskStreaming(ctx, taskID, execOpts)
require.NoError(t, err)
select {
case err := <-errCh:
require.NoError(t, err)
default:
// all good
}
exitCode = r.ExitCode
} else {
require.Fail(t, "driver does not support exec")
}
result := stream.currentResult()
require.NoError(t, result.err)
if !isRaw {
result.exitCode = exitCode
}
return result
}
type execResult struct {
exitCode int
stdout string
stderr string
err error
}
func newTestExecStream(t *testing.T, tty bool, stdin string) *testExecStream {
return &testExecStream{
t: t,
input: newInputStream(tty, stdin),
result: &execResult{exitCode: -2},
}
}
func newInputStream(tty bool, stdin string) []*drivers.ExecTaskStreamingRequestMsg {
input := []*drivers.ExecTaskStreamingRequestMsg{}
if tty {
// emit two resize to ensure we honor latest
input = append(input, &drivers.ExecTaskStreamingRequestMsg{
TtySize: &dproto.ExecTaskStreamingRequest_TerminalSize{
Height: 50,
Width: 40,
}})
input = append(input, &drivers.ExecTaskStreamingRequestMsg{
TtySize: &dproto.ExecTaskStreamingRequest_TerminalSize{
Height: 100,
Width: 100,
}})
}
input = append(input, &drivers.ExecTaskStreamingRequestMsg{
Stdin: &dproto.ExecTaskStreamingIOOperation{
Data: []byte(stdin),
},
})
if !tty {
// don't close stream in interactive session and risk closing tty prematurely
input = append(input, &drivers.ExecTaskStreamingRequestMsg{
Stdin: &dproto.ExecTaskStreamingIOOperation{
Close: true,
},
})
}
return input
}
var _ drivers.ExecTaskStream = (*testExecStream)(nil)
type testExecStream struct {
t *testing.T
// input
input []*drivers.ExecTaskStreamingRequestMsg
recvCalled int
// result so far
resultLock sync.Mutex
result *execResult
}
func (s *testExecStream) currentResult() execResult {
s.resultLock.Lock()
defer s.resultLock.Unlock()
// make a copy
return *s.result
}
func (s *testExecStream) Recv() (*drivers.ExecTaskStreamingRequestMsg, error) {
if s.recvCalled >= len(s.input) {
return nil, io.EOF
}
i := s.input[s.recvCalled]
s.recvCalled++
return i, nil
}
func (s *testExecStream) Send(m *drivers.ExecTaskStreamingResponseMsg) error {
s.resultLock.Lock()
defer s.resultLock.Unlock()
switch {
case m.Stdout != nil && m.Stdout.Data != nil:
s.t.Logf("received stdout: %s", string(m.Stdout.Data))
s.result.stdout += string(m.Stdout.Data)
case m.Stderr != nil && m.Stderr.Data != nil:
s.t.Logf("received stderr: %s", string(m.Stderr.Data))
s.result.stderr += string(m.Stderr.Data)
case m.Exited && m.Result != nil:
s.result.exitCode = int(m.Result.ExitCode)
}
return nil
}