forked from kedacore/http-add-on
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathproxy_handlers_integration_test.go
380 lines (349 loc) · 9.2 KB
/
proxy_handlers_integration_test.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
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
package main
import (
"context"
"fmt"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"strings"
"testing"
"time"
"github.com/go-logr/logr"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/sync/errgroup"
appsv1 "k8s.io/api/apps/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
"github.com/kedacore/http-add-on/pkg/k8s"
kedanet "github.com/kedacore/http-add-on/pkg/net"
"github.com/kedacore/http-add-on/pkg/routing"
)
// happy path - deployment is scaled to 1 and host in routing table
func TestIntegrationHappyPath(t *testing.T) {
const (
deploymentReplicasTimeout = 200 * time.Millisecond
responseHeaderTimeout = 1 * time.Second
deplName = "testdeployment"
namespace = "testns"
)
r := require.New(t)
h, err := newHarness(
t,
deploymentReplicasTimeout,
)
r.NoError(err)
defer h.close()
t.Logf("Harness: %s", h.String())
h.deplCache.Set(namespace, deplName, appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{Name: deplName},
Spec: appsv1.DeploymentSpec{
// note that the forwarding wait function doesn't care about
// the replicas field, it only cares about ReadyReplicas in the status.
// regardless, we're setting this because in a running cluster,
// it's likely that most of the time, this is equal to ReadyReplicas
Replicas: i32Ptr(3),
},
Status: appsv1.DeploymentStatus{
ReadyReplicas: 3,
},
})
originPort, err := strconv.Atoi(h.originURL.Port())
r.NoError(err)
r.NoError(h.routingTable.AddTarget(hostForTest(t), targetFromURL(
h.originURL,
originPort,
deplName,
)))
// happy path
res, err := doRequest(
http.DefaultClient,
h.proxyURL.String(),
hostForTest(t),
)
r.NoError(err)
r.Equal(200, res.StatusCode)
res.Body.Close()
}
// deployment scaled to 1 but host not in routing table
//
// NOTE: the interceptor needs to check in the routing table
// _before_ checking the deployment cache, so we don't technically
// need to set the replicas to 1, but we're doing so anyway to
// isolate the routing table behavior
func TestIntegrationNoRoutingTableEntry(t *testing.T) {
const (
ns = "testns"
)
host := fmt.Sprintf("%s.integrationtest.interceptor.kedahttp.dev", t.Name())
r := require.New(t)
h, err := newHarness(t, time.Second)
r.NoError(err)
defer h.close()
h.deplCache.Set(ns, host, appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{Name: host},
Spec: appsv1.DeploymentSpec{
Replicas: i32Ptr(1),
},
})
// not in the routing table
res, err := doRequest(
http.DefaultClient,
h.proxyURL.String(),
"not-in-the-table",
)
res.Body.Close()
r.NoError(err)
r.Equal(404, res.StatusCode)
res.Body.Close()
}
// host in the routing table but deployment has no replicas
func TestIntegrationNoReplicas(t *testing.T) {
const (
deployTimeout = 100 * time.Millisecond
ns = "testns"
)
host := hostForTest(t)
deployName := "testdeployment"
r := require.New(t)
h, err := newHarness(t, deployTimeout)
r.NoError(err)
originPort, err := strconv.Atoi(h.originURL.Port())
r.NoError(err)
r.NoError(h.routingTable.AddTarget(hostForTest(t), targetFromURL(
h.originURL,
originPort,
deployName,
)))
// 0 replicas
h.deplCache.Set(ns, deployName, appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{Name: deployName},
Spec: appsv1.DeploymentSpec{
Replicas: i32Ptr(0),
},
})
start := time.Now()
res, err := doRequest(
http.DefaultClient,
h.proxyURL.String(),
host,
)
r.NoError(err)
r.Equal(502, res.StatusCode)
res.Body.Close()
elapsed := time.Since(start)
// we should have slept more than the deployment replicas wait timeout
r.GreaterOrEqual(elapsed, deployTimeout)
r.Less(elapsed, deployTimeout+50*time.Millisecond)
}
// the request comes in while there are no replicas, and one is added
// while it's pending
func TestIntegrationWaitReplicas(t *testing.T) {
const (
deployTimeout = 2 * time.Second
responseTimeout = 1 * time.Second
ns = "testns"
deployName = "testdeployment"
)
ctx := context.Background()
r := require.New(t)
h, err := newHarness(t, deployTimeout)
r.NoError(err)
// add host to routing table
originPort, err := strconv.Atoi(h.originURL.Port())
r.NoError(err)
r.NoError(h.routingTable.AddTarget(
hostForTest(t),
targetFromURL(
h.originURL,
originPort,
deployName,
),
))
// set up a deployment with zero replicas and create
// a watcher we can use later to fake-send a deployment
// event
initialDeployment := appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{Name: deployName},
Spec: appsv1.DeploymentSpec{
Replicas: i32Ptr(0),
},
}
h.deplCache.Set(ns, deployName, initialDeployment)
watcher := h.deplCache.SetWatcher(ns, deployName)
// make the request in one goroutine, and in the other, wait a bit
// and then add replicas to the deployment cache
var response *http.Response
grp, _ := errgroup.WithContext(ctx)
grp.Go(func() error {
resp, err := doRequest(
http.DefaultClient,
h.proxyURL.String(),
hostForTest(t),
)
if err != nil {
return err
}
response = resp
resp.Body.Close()
return nil
})
const sleepDur = deployTimeout / 4
grp.Go(func() error {
t.Logf("Sleeping for %s", sleepDur)
time.Sleep(sleepDur)
t.Logf("Woke up, setting replicas to 10")
modifiedDeployment := initialDeployment.DeepCopy()
// note that the wait function only cares about Status.ReadyReplicas
// but we're setting Spec.Replicas to 10 as well because the common
// case in the cluster is that they would be equal
modifiedDeployment.Spec.Replicas = i32Ptr(10)
modifiedDeployment.Status.ReadyReplicas = 10
// send a watch event (instead of setting replicas) so that the watch
// func sees that it can forward the request now
watcher.Modify(modifiedDeployment)
return nil
})
start := time.Now()
r.NoError(grp.Wait())
elapsed := time.Since(start)
// assert here so that we can check all of these cases
// rather than just failing at the first one
a := assert.New(t)
a.GreaterOrEqual(elapsed, sleepDur)
a.Less(
elapsed,
sleepDur*2,
"the handler took too long. this is usually because it timed out, not because it didn't find the watch event in time",
)
a.Equal(200, response.StatusCode)
}
func doRequest(
cl *http.Client,
urlStr,
host string,
) (*http.Response, error) {
req, err := http.NewRequest("GET", urlStr, nil)
if err != nil {
return nil, err
}
req.Host = host
res, err := cl.Do(req)
if err != nil {
return nil, err
}
return res, nil
}
type harness struct {
lggr logr.Logger
proxyHdl http.Handler
proxySrv *httptest.Server
proxyURL *url.URL
originHdl http.Handler
originSrv *httptest.Server
originURL *url.URL
routingTable *routing.Table
dialCtxFunc kedanet.DialContextFunc
deplCache *k8s.FakeDeploymentCache
waitFunc forwardWaitFunc
}
func newHarness(
t *testing.T,
deployReplicasTimeout time.Duration,
) (*harness, error) {
t.Helper()
lggr := logr.Discard()
routingTable := routing.NewTable()
dialContextFunc := kedanet.DialContextWithRetry(
&net.Dialer{
Timeout: 2 * time.Second,
},
wait.Backoff{
Steps: 2,
Duration: time.Second,
},
)
deplCache := k8s.NewFakeDeploymentCache()
waitFunc := newDeployReplicasForwardWaitFunc(
logr.Discard(),
deplCache,
)
originHdl := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte("hello!"))
if err != nil {
t.Fatalf("error writing message from origin: %s", err)
}
})
testOriginSrv, originSrvURL, err := kedanet.StartTestServer(originHdl)
if err != nil {
return nil, err
}
proxyHdl := newForwardingHandler(
lggr,
routingTable,
dialContextFunc,
waitFunc,
func(routing.Target) (*url.URL, error) {
return originSrvURL, nil
},
forwardingConfig{
waitTimeout: deployReplicasTimeout,
respHeaderTimeout: time.Second,
},
)
proxySrv, proxySrvURL, err := kedanet.StartTestServer(proxyHdl)
if err != nil {
return nil, err
}
return &harness{
lggr: lggr,
proxyHdl: proxyHdl,
proxySrv: proxySrv,
proxyURL: proxySrvURL,
originHdl: originHdl,
originSrv: testOriginSrv,
originURL: originSrvURL,
routingTable: routingTable,
dialCtxFunc: dialContextFunc,
deplCache: deplCache,
waitFunc: waitFunc,
}, nil
}
func (h *harness) close() {
h.proxySrv.Close()
h.originSrv.Close()
}
func (h *harness) String() string {
return fmt.Sprintf(
"harness{proxy: %s, origin: %s}",
h.proxyURL.String(),
h.originURL.String(),
)
}
func i32Ptr(i int32) *int32 {
return &i
}
func hostForTest(t *testing.T) string {
t.Helper()
return fmt.Sprintf("%s.integrationtest.interceptor.kedahttp.dev", t.Name())
}
// similar to net.SplitHostPort (https://pkg.go.dev/net#SplitHostPort)
// but returns the port as a string, not an int.
//
// useful because url.Host can contain the port, so ensure we only get the actual host
func splitHostPort(hostPortStr string) (string, int, error) {
spl := strings.Split(hostPortStr, ":")
if len(spl) != 2 {
return "", 0, fmt.Errorf("invalid host:port: %s", hostPortStr)
}
host := spl[0]
port, err := strconv.Atoi(spl[1])
if err != nil {
return "", 0, errors.Wrap(err, "port was invalid")
}
return host, port, nil
}