aboutsummaryrefslogtreecommitdiff
path: root/pkg/hooks/exec/exec_test.go
blob: 7aac315cb5db841522ba9663af4b6e4ec40c03f1 (plain)
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
package exec

import (
	"bytes"
	"context"
	"fmt"
	"os"
	"runtime"
	"strings"
	"testing"
	"time"

	rspec "github.com/opencontainers/runtime-spec/specs-go"
	"github.com/stretchr/testify/assert"
)

// path is the path to an example hook executable.
var path string

// unavoidableEnvironmentKeys may be injected even if the hook
// executable is executed with a requested empty environment.
var unavoidableEnvironmentKeys []string

func TestRun(t *testing.T) {
	ctx := context.Background()
	hook := &rspec.Hook{
		Path: path,
		Args: []string{"sh", "-c", "cat"},
	}
	var stderr, stdout bytes.Buffer
	hookErr, err := Run(ctx, hook, []byte("{}"), &stdout, &stderr, DefaultPostKillTimeout)
	if err != nil {
		t.Fatal(err)
	}
	if hookErr != nil {
		t.Fatal(hookErr)
	}
	assert.Equal(t, "{}", stdout.String())
	assert.Equal(t, "", stderr.String())
}

func TestRunIgnoreOutput(t *testing.T) {
	ctx := context.Background()
	hook := &rspec.Hook{
		Path: path,
		Args: []string{"sh", "-c", "cat"},
	}
	hookErr, err := Run(ctx, hook, []byte("{}"), nil, nil, DefaultPostKillTimeout)
	if err != nil {
		t.Fatal(err)
	}
	if hookErr != nil {
		t.Fatal(hookErr)
	}
}

func TestRunFailedStart(t *testing.T) {
	ctx := context.Background()
	hook := &rspec.Hook{
		Path: "/does/not/exist",
	}
	hookErr, err := Run(ctx, hook, []byte("{}"), nil, nil, DefaultPostKillTimeout)
	if err == nil {
		t.Fatal("unexpected success")
	}
	if !os.IsNotExist(err) {
		t.Fatal(err)
	}
	assert.Equal(t, err, hookErr)
}

func parseEnvironment(input string) (env map[string]string, err error) {
	env = map[string]string{}
	lines := strings.Split(input, "\n")
	for i, line := range lines {
		if line == "" && i == len(lines)-1 {
			continue // no content after the terminal newline
		}
		keyValue := strings.SplitN(line, "=", 2)
		if len(keyValue) < 2 {
			return env, fmt.Errorf("no = in environment line: %q", line)
		}
		env[keyValue[0]] = keyValue[1]
	}
	for _, key := range unavoidableEnvironmentKeys {
		delete(env, key)
	}
	return env, nil
}

func TestRunEnvironment(t *testing.T) {
	ctx := context.Background()
	hook := &rspec.Hook{
		Path: path,
		Args: []string{"sh", "-c", "env"},
	}
	for _, test := range []struct {
		name     string
		env      []string
		expected map[string]string
	}{
		{
			name:     "unset",
			expected: map[string]string{},
		},
		{
			name:     "set empty",
			env:      []string{},
			expected: map[string]string{},
		},
		{
			name: "set",
			env: []string{
				"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
				"TERM=xterm",
			},
			expected: map[string]string{
				"PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
				"TERM": "xterm",
			},
		},
	} {
		t.Run(test.name, func(t *testing.T) {
			var stderr, stdout bytes.Buffer
			hook.Env = test.env
			hookErr, err := Run(ctx, hook, []byte("{}"), &stdout, &stderr, DefaultPostKillTimeout)
			if err != nil {
				t.Fatal(err)
			}
			if hookErr != nil {
				t.Fatal(hookErr)
			}
			assert.Equal(t, "", stderr.String())

			env, err := parseEnvironment(stdout.String())
			if err != nil {
				t.Fatal(err)
			}
			assert.Equal(t, test.expected, env)
		})
	}
}

func TestRunCancel(t *testing.T) {
	hook := &rspec.Hook{
		Path: path,
		Args: []string{"sh", "-c", "echo waiting; sleep 2; echo done"},
	}
	one := 1
	for _, test := range []struct {
		name              string
		contextTimeout    time.Duration
		hookTimeout       *int
		expectedHookError string
		expectedRunError  error
		expectedStdout    string
	}{
		{
			name:           "no timeouts",
			expectedStdout: "waiting\ndone\n",
		},
		{
			name:              "context timeout",
			contextTimeout:    time.Duration(1) * time.Second,
			expectedStdout:    "waiting\n",
			expectedHookError: "^executing \\[sh -c echo waiting; sleep 2; echo done]: signal: killed$",
			expectedRunError:  context.DeadlineExceeded,
		},
		{
			name:              "hook timeout",
			hookTimeout:       &one,
			expectedStdout:    "waiting\n",
			expectedHookError: "^executing \\[sh -c echo waiting; sleep 2; echo done]: signal: killed$",
			expectedRunError:  context.DeadlineExceeded,
		},
	} {
		t.Run(test.name, func(t *testing.T) {
			ctx := context.Background()
			var stderr, stdout bytes.Buffer
			if test.contextTimeout > 0 {
				var cancel context.CancelFunc
				ctx, cancel = context.WithTimeout(ctx, test.contextTimeout)
				defer cancel()
			}
			hook.Timeout = test.hookTimeout
			hookErr, err := Run(ctx, hook, []byte("{}"), &stdout, &stderr, DefaultPostKillTimeout)
			assert.Equal(t, test.expectedRunError, err)
			if test.expectedHookError == "" {
				if hookErr != nil {
					t.Fatal(hookErr)
				}
			} else {
				assert.Regexp(t, test.expectedHookError, hookErr.Error())
			}
			assert.Equal(t, "", stderr.String())
			assert.Equal(t, test.expectedStdout, stdout.String())
		})
	}
}

func TestRunKillTimeout(t *testing.T) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Duration(500)*time.Millisecond)
	defer cancel()
	hook := &rspec.Hook{
		Path: path,
		Args: []string{"sh", "-c", "sleep 1"},
	}
	hookErr, err := Run(ctx, hook, []byte("{}"), nil, nil, time.Duration(0))
	assert.Equal(t, context.DeadlineExceeded, err)
	assert.Regexp(t, "^(failed to reap process within 0s of the kill signal|executing \\[sh -c sleep 1]: signal: killed)$", hookErr)
}

func init() {
	if runtime.GOOS != "windows" {
		path = "/bin/sh"
		unavoidableEnvironmentKeys = []string{"PWD", "SHLVL", "_"}
	} else {
		panic("we need a reliable executable path on Windows")
	}
}