Debian Codegraph @

tests/proxy_test.go

raw symbols SCIP
1 /*
2 Copyright 2022 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package tests
18
19 import (
20 "bufio"
21 "context"
22 "fmt"
23 "io"
24 "math/rand"
25 "net"
26 "net/http"
27 "net/http/httptest"
28 "net/url"
29 "path/filepath"
30 "strings"
31 "sync"
32 "testing"
33 "time"
34
35 "github.com/google/uuid"
36 "go.uber.org/goleak"
37 "google.golang.org/grpc"
38 "google.golang.org/grpc/credentials"
39 "google.golang.org/grpc/credentials/insecure"
40 "google.golang.org/grpc/metadata"
41 "k8s.io/apimachinery/pkg/util/wait"
42 "sigs.k8s.io/apiserver-network-proxy/konnectivity-client/pkg/client"
43 metricsclient "sigs.k8s.io/apiserver-network-proxy/konnectivity-client/pkg/client/metrics"
44 clientmetricstest "sigs.k8s.io/apiserver-network-proxy/konnectivity-client/pkg/common/metrics/testing"
45 metricsagent "sigs.k8s.io/apiserver-network-proxy/pkg/agent/metrics"
46 "sigs.k8s.io/apiserver-network-proxy/pkg/server"
47 metricsserver "sigs.k8s.io/apiserver-network-proxy/pkg/server/metrics"
48 metricstest "sigs.k8s.io/apiserver-network-proxy/pkg/testing/metrics"
49 "sigs.k8s.io/apiserver-network-proxy/pkg/util"
50 agentproto "sigs.k8s.io/apiserver-network-proxy/proto/agent"
51 "sigs.k8s.io/apiserver-network-proxy/proto/header"
52 "sigs.k8s.io/apiserver-network-proxy/tests/framework"
53 )
54
55 // Define a blackholed address, for which Dial is expected to hang. This address is reserved for
56 // benchmarking by RFC 6890.
57 const blackhole = "198.18.0.254:1234"
58
59 // test remote server
60 type testServer struct {
61 echo []byte
62 chunks int
63 }
64
65 func newEchoServer(echo string) *testServer {
66 return &testServer{
67 echo: []byte(echo),
68 chunks: 1,
69 }
70 }
71
72 func newSizedServer(length, chunks int) *testServer {
73 return &testServer{
74 echo: make([]byte, length),
75 chunks: chunks,
76 }
77 }
78
79 func (s *testServer) ServeHTTP(w http.ResponseWriter, _ *http.Request) {
80 for i := 0; i < s.chunks; i++ {
81 w.Write(s.echo)
82 }
83 }
84
85 type waitingServer struct {
86 requestReceivedCh chan struct{} // channel is closed when the server receives a request
87 respondCh chan struct{} // server responds when this channel is closed
88 }
89
90 func newWaitingServer() *waitingServer {
91 return &waitingServer{
92 requestReceivedCh: make(chan struct{}),
93 respondCh: make(chan struct{}),
94 }
95 }
96
97 func (s *waitingServer) ServeHTTP(w http.ResponseWriter, _ *http.Request) {
98 close(s.requestReceivedCh)
99 <-s.respondCh // Wait for permission to respond.
100 w.Write([]byte("hello"))
101 }
102
103 type delayedServer struct {
104 minWait time.Duration
105 maxWait time.Duration
106 }
107
108 // randomDuration returns a random duration in the [lower, upper) interval
109 // Cannot use min/max because linter gives the following error.
110 // "redefines-builtin-id: redefinition of the built-in function min (revive)"
111 func randomDuration(lower, upper time.Duration) time.Duration {
112 d := lower
113 if upper != lower {
114 d += time.Duration(rand.Int63n(int64(upper - lower)))
115 }
116 return d
117 }
118
119 func newDelayedServer(minWait time.Duration, maxWait time.Duration) *delayedServer {
120 return &delayedServer{
121 minWait: minWait,
122 maxWait: maxWait,
123 }
124 }
125
126 var _ = newDelayedServer(time.Second, time.Second) // Suppress unused lint error.
127
128 func (s *delayedServer) ServeHTTP(w http.ResponseWriter, _ *http.Request) {
129 delay := randomDuration(s.minWait, s.maxWait)
130 time.Sleep(delay)
131 w.Write([]byte("hello"))
132 }
133
134 func TestBasicProxy_GRPC(t *testing.T) {
135 expectCleanShutdown(t)
136
137 server := httptest.NewServer(newEchoServer("hello"))
138 defer server.Close()
139
140 ps := runGRPCProxyServer(t)
141 defer ps.Stop()
142
143 a := runAgent(t, ps.AgentAddr())
144 defer a.Stop()
145 waitForConnectedServerCount(t, 1, a)
146
147 // run test client
148 ctx, cancel := context.WithCancel(context.Background())
149 defer cancel()
150 tunnel, err := createSingleUseGrpcTunnel(ctx, ps.FrontAddr())
151 if err != nil {
152 t.Fatal(err)
153 }
154
155 c := &http.Client{
156 Transport: &http.Transport{
157 DialContext: tunnel.DialContext,
158 },
159 }
160
161 req, err := http.NewRequest("GET", server.URL, nil)
162 if err != nil {
163 t.Fatal(err)
164 }
165
166 r, err := c.Do(req)
167 if err != nil {
168 t.Fatal(err)
169 }
170 defer r.Body.Close()
171
172 data, err := io.ReadAll(r.Body)
173 if err != nil {
174 t.Fatal(err)
175 }
176 if string(data) != "hello" {
177 t.Errorf("expect %v; got %v", "hello", string(data))
178 }
179 }
180
181 func TestProxyHandleDialError_GRPC(t *testing.T) {
182 expectCleanShutdown(t)
183
184 ctx := context.Background()
185 invalidServer := httptest.NewServer(newEchoServer("hello"))
186
187 ps := runGRPCProxyServer(t)
188 defer ps.Stop()
189
190 a := runAgent(t, ps.AgentAddr())
191 defer a.Stop()
192 waitForConnectedServerCount(t, 1, a)
193
194 // run test client
195 tunnel, err := createSingleUseGrpcTunnel(ctx, ps.FrontAddr())
196 if err != nil {
197 t.Fatal(err)
198 }
199
200 c := &http.Client{
201 Transport: &http.Transport{
202 DialContext: tunnel.DialContext,
203 },
204 }
205
206 url := invalidServer.URL
207 invalidServer.Close()
208
209 _, err = c.Get(url)
210 if err == nil {
211 t.Error("Expected error when destination is unreachable, did not receive error")
212 } else if !strings.Contains(err.Error(), "connection refused") {
213 t.Errorf("Unexpected error: %v", err)
214 }
215
216 if err := ps.Metrics().ExpectServerDialFailure(metricsserver.DialFailureErrorResponse, 1); err != nil {
217 t.Error(err)
218 }
219 if err := a.Metrics().ExpectAgentDialFailure(metricsagent.DialFailureUnknown, 1); err != nil {
220 t.Error(err)
221 }
222 resetAllMetrics() // For clean shutdown.
223 }
224
225 func TestProxyHandle_DoneContext_GRPC(t *testing.T) {
226 expectCleanShutdown(t)
227
228 server := httptest.NewServer(newEchoServer("hello"))
229 defer server.Close()
230
231 ps := runGRPCProxyServer(t)
232 defer ps.Stop()
233
234 a := runAgent(t, ps.AgentAddr())
235 defer a.Stop()
236 waitForConnectedServerCount(t, 1, a)
237
238 // run test client
239 ctx, cancel := context.WithTimeout(context.Background(), -time.Second)
240 defer cancel()
241 _, err := createSingleUseGrpcTunnel(ctx, ps.FrontAddr())
242 if err == nil {
243 t.Error("Expected error when context is cancelled, did not receive error")
244 } else if !strings.Contains(err.Error(), "context deadline exceeded") {
245 t.Errorf("Unexpected error: %v", err)
246 }
247 }
248
249 func TestProxyHandle_RequestDeadlineExceeded_GRPC(t *testing.T) {
250 expectCleanShutdown(t)
251
252 slowServer := newWaitingServer()
253 server := httptest.NewServer(slowServer)
254 defer server.Close()
255
256 ps := runGRPCProxyServer(t)
257 defer ps.Stop()
258
259 a := runAgent(t, ps.AgentAddr())
260 defer a.Stop()
261 waitForConnectedServerCount(t, 1, a)
262
263 func() {
264 // Ensure that tunnels aren't leaked with long-running servers.
265 ignoredGoRoutines := []goleak.Option{
266 goleak.IgnoreCurrent(),
267 goleak.IgnoreTopFunction("google.golang.org/grpc.(*addrConn).resetTransport"),
268 goleak.IgnoreTopFunction("google.golang.org/grpc.(*addrConn).resetTransportAndUnlock"),
269 }
270 defer goleak.VerifyNone(t, ignoredGoRoutines...)
271
272 // run test client
273 tunnel, err := createSingleUseGrpcTunnel(context.Background(), ps.FrontAddr())
274 if err != nil {
275 t.Fatal(err)
276 }
277
278 ctx, cancel := context.WithTimeout(context.Background(), time.Second)
279 defer cancel()
280 go func() {
281 <-ctx.Done() // Wait for context to time out.
282 close(slowServer.respondCh)
283 }()
284
285 c := &http.Client{
286 Transport: &http.Transport{
287 DialContext: tunnel.DialContext,
288 },
289 }
290
291 req, err := http.NewRequestWithContext(ctx, "GET", server.URL, nil)
292 if err != nil {
293 t.Fatal(err)
294 }
295
296 _, err = c.Do(req)
297 if err == nil {
298 t.Error("Expected error when context is cancelled, did not receive error")
299 } else if !strings.Contains(err.Error(), "context deadline exceeded") {
300 t.Errorf("Unexpected error: %v", err)
301 }
302
303 t.Log("Wait for tunnel to close")
304 select {
305 case <-tunnel.Done():
306 t.Log("Tunnel closed successfully")
307 case <-time.After(framework.ForeverTestTimeout):
308 t.Errorf("Timed out waiting for tunnel to close")
309 }
310 }()
311 }
312
313 func TestProxyDial_RequestCancelled_GRPC(t *testing.T) {
314 expectCleanShutdown(t)
315
316 ps := runGRPCProxyServer(t)
317 defer ps.Stop()
318
319 agent := &unresponsiveAgent{}
320 if err := agent.Connect(ps.AgentAddr()); err != nil {
321 t.Fatalf("Failed to connect unresponsive agent: %v", err)
322 }
323 defer agent.Close()
324 waitForConnectedAgentCount(t, 1, ps)
325
326 func() {
327 // Ensure that tunnels aren't leaked with long-running servers.
328 ignoredGoRoutines := []goleak.Option{
329 goleak.IgnoreCurrent(),
330 goleak.IgnoreTopFunction("google.golang.org/grpc.(*addrConn).resetTransport"),
331 goleak.IgnoreTopFunction("google.golang.org/grpc.(*addrConn).resetTransportAndUnlock"),
332 }
333 defer goleak.VerifyNone(t, ignoredGoRoutines...)
334
335 // run test client
336 tunnel, err := createSingleUseGrpcTunnel(context.Background(), ps.FrontAddr())
337 if err != nil {
338 t.Fatal(err)
339 }
340
341 ctx, cancel := context.WithCancel(context.Background())
342
343 go func() {
344 time.Sleep(1 * time.Second)
345 cancel() // Cancel the request (client-side)
346 }()
347
348 _, err = tunnel.DialContext(ctx, "tcp", blackhole)
349 if err == nil {
350 t.Error("Expected error when context is cancelled, did not receive error")
351 } else if _, reason := client.GetDialFailureReason(err); reason != metricsclient.DialFailureContext {
352 t.Errorf("Unexpected error: %v", err)
353 }
354
355 select {
356 case <-tunnel.Done():
357 case <-time.After(framework.ForeverTestTimeout):
358 t.Errorf("Timed out waiting for tunnel to close")
359 }
360 }()
361
362 if err := clientmetricstest.ExpectClientDialFailure(metricsclient.DialFailureContext, 1); err != nil {
363 t.Error(err)
364 }
365 if err := ps.Metrics().ExpectServerDialFailure(metricsserver.DialFailureFrontendClose, 1); err != nil {
366 t.Error(err)
367 }
368 resetAllMetrics() // For clean shutdown.
369 }
370
371 func TestProxyDial_RequestCancelled_Concurrent_GRPC(t *testing.T) {
372 expectCleanShutdown(t)
373
374 // An HTTP server that always waits 3 seconds before replying
375 slowServer := newDelayedServer(3*time.Second, 3*time.Second)
376 server := httptest.NewServer(slowServer)
377 defer server.Close()
378
379 ps := runGRPCProxyServer(t)
380 defer ps.Stop()
381
382 a := runAgent(t, ps.AgentAddr())
383 defer a.Stop()
384 waitForConnectedServerCount(t, 1, a)
385
386 wg := sync.WaitGroup{}
387 dialFn := func(_ int, cancelDelay time.Duration) {
388 defer wg.Done()
389
390 // run test client
391 tunnel, err := createSingleUseGrpcTunnel(context.Background(), ps.FrontAddr())
392 if err != nil {
393 t.Error(err)
394 return
395 }
396
397 ctx, cancel := context.WithCancel(context.Background())
398
399 go func() {
400 time.Sleep(cancelDelay)
401 cancel() // Cancel the request (client-side)
402 }()
403
404 c := &http.Client{
405 Transport: &http.Transport{
406 DialContext: tunnel.DialContext,
407 },
408 }
409
410 req, err := http.NewRequestWithContext(ctx, "GET", server.URL, nil)
411 if err != nil {
412 t.Error(err)
413 return
414 }
415
416 c.Do(req) // Errors are expected.
417
418 select {
419 case <-tunnel.Done():
420 case <-time.After(framework.ForeverTestTimeout):
421 t.Errorf("Timed out waiting for tunnel to close")
422 }
423 }
424
425 // Ensure that tunnels aren't leaked with long-running servers.
426 ignoredGoRoutines := []goleak.Option{
427 goleak.IgnoreCurrent(),
428 goleak.IgnoreTopFunction("google.golang.org/grpc.(*addrConn).resetTransport"),
429 goleak.IgnoreTopFunction("google.golang.org/grpc.(*addrConn).resetTransportAndUnlock"),
430 }
431
432 const concurrentConns = 50
433 wg.Add(concurrentConns)
434 for i := 0; i < concurrentConns; i++ {
435 // The delay before we cancel the HTTP request:
436 // * at least 1 second for the HTTP connection to establish
437 // * less than 2 seconds so that we cancel during the 3 second delay in our slowServer
438 // TODO: Can we try to cancel during the dial? Or after the HTTP request has returned?
439 cancelDelay := randomDuration(time.Second, 2*time.Second)
440 go dialFn(i, cancelDelay)
441 }
442 wg.Wait()
443
444 // Wait for the closed connections to propogate
445 var endpointConnsErr, goLeaksErr error
446 wait.PollImmediate(time.Second, framework.ForeverTestTimeout, func() (done bool, err error) {
447 endpointConnsErr = a.Metrics().ExpectAgentEndpointConnections(0)
448 goLeaksErr = goleak.Find(ignoredGoRoutines...)
449 return endpointConnsErr == nil && goLeaksErr == nil, nil
450 })
451
452 if endpointConnsErr != nil {
453 t.Errorf("Agent connections leaked: %v", endpointConnsErr)
454 }
455 if goLeaksErr != nil {
456 t.Error(goLeaksErr)
457 }
458
459 resetAllMetrics() // For clean shutdown.
460 }
461
462 func TestProxyDial_AgentTimeout_GRPC(t *testing.T) {
463 expectCleanShutdown(t)
464
465 ps := runGRPCProxyServer(t)
466 defer ps.Stop()
467
468 a := runAgent(t, ps.AgentAddr())
469 defer a.Stop()
470 waitForConnectedServerCount(t, 1, a)
471
472 func() {
473 // Ensure that tunnels aren't leaked with long-running servers.
474 ignoredGoRoutines := []goleak.Option{
475 goleak.IgnoreCurrent(),
476 goleak.IgnoreTopFunction("google.golang.org/grpc.(*addrConn).resetTransport"),
477 goleak.IgnoreTopFunction("google.golang.org/grpc.(*addrConn).resetTransportAndUnlock"),
478 }
479 defer goleak.VerifyNone(t, ignoredGoRoutines...)
480
481 // run test client
482 tunnel, err := createSingleUseGrpcTunnel(context.Background(), ps.FrontAddr())
483 if err != nil {
484 t.Fatal(err)
485 }
486
487 // Agent should time out after 5 seconds and return a DIAL_RSP with an error.
488 _, err = tunnel.DialContext(context.Background(), "tcp", blackhole)
489 if err == nil {
490 t.Error("Expected error when context is cancelled, did not receive error")
491 } else if _, reason := client.GetDialFailureReason(err); reason != metricsclient.DialFailureEndpoint {
492 t.Errorf("Unexpected error: %v", err)
493 }
494
495 if err := clientmetricstest.ExpectClientDialFailure(metricsclient.DialFailureEndpoint, 1); err != nil {
496 t.Error(err)
497 }
498 if err := ps.Metrics().ExpectServerDialFailure(metricsserver.DialFailureErrorResponse, 1); err != nil {
499 t.Error(err)
500 }
501 if err := a.Metrics().ExpectAgentDialFailure(metricsagent.DialFailureTimeout, 1); err != nil {
502 t.Error(err)
503 }
504 resetAllMetrics() // For clean shutdown.
505
506 select {
507 case <-tunnel.Done():
508 case <-time.After(framework.ForeverTestTimeout):
509 t.Errorf("Timed out waiting for tunnel to close")
510 }
511 }()
512 }
513
514 func TestProxyHandle_TunnelContextCancelled_GRPC(t *testing.T) {
515 expectCleanShutdown(t)
516
517 slowServer := newWaitingServer()
518 server := httptest.NewServer(slowServer)
519 defer server.Close()
520
521 ps := runGRPCProxyServer(t)
522 defer ps.Stop()
523
524 a := runAgent(t, ps.AgentAddr())
525 defer a.Stop()
526 waitForConnectedServerCount(t, 1, a)
527
528 // run test client
529 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
530 tunnel, err := createSingleUseGrpcTunnel(ctx, ps.FrontAddr())
531 if err != nil {
532 t.Fatal(err)
533 }
534
535 go func() {
536 <-slowServer.requestReceivedCh // Wait for server to receive request.
537 cancel()
538 close(slowServer.respondCh) // Unblock server response.
539 }()
540
541 c := &http.Client{
542 Transport: &http.Transport{
543 DialContext: tunnel.DialContext,
544 },
545 }
546
547 // TODO: handle case where there is no context on the request.
548 req, err := http.NewRequestWithContext(ctx, "GET", server.URL, nil)
549 if err != nil {
550 t.Error(err)
551 }
552
553 _, err = c.Do(req)
554 if err == nil {
555 t.Error("Expected error when context is cancelled, did not receive error")
556 } else if !strings.Contains(err.Error(), "context canceled") {
557 t.Errorf("Unexpected error: %v", err)
558 }
559 }
560
561 func TestProxy_LargeResponse(t *testing.T) {
562 expectCleanShutdown(t)
563
564 ctx := context.Background()
565 length := 1 << 20 // 1M
566 chunks := 10
567 server := httptest.NewServer(newSizedServer(length, chunks))
568 defer server.Close()
569
570 ps := runGRPCProxyServer(t)
571 defer ps.Stop()
572
573 a := runAgent(t, ps.AgentAddr())
574 defer a.Stop()
575 waitForConnectedServerCount(t, 1, a)
576
577 // run test client
578 tunnel, err := createSingleUseGrpcTunnel(ctx, ps.FrontAddr())
579 if err != nil {
580 t.Fatal(err)
581 }
582
583 c := &http.Client{
584 Transport: &http.Transport{
585 DialContext: tunnel.DialContext,
586 },
587 }
588
589 req, err := http.NewRequest("GET", server.URL, nil)
590 if err != nil {
591 t.Error(err)
592 }
593 req.Close = true
594
595 r, err := c.Do(req)
596 if err != nil {
597 t.Error(err)
598 }
599
600 data, err := io.ReadAll(r.Body)
601 r.Body.Close()
602 if err != nil {
603 t.Error(err)
604 }
605
606 if len(data) != length*chunks {
607 t.Errorf("expect data length %d; got %d", length*chunks, len(data))
608 }
609 }
610
611 func TestBasicProxy_HTTPCONN(t *testing.T) {
612 expectCleanShutdown(t)
613
614 server := httptest.NewServer(newEchoServer("hello"))
615 defer server.Close()
616
617 ps := runHTTPConnProxyServer(t)
618 defer ps.Stop()
619
620 a := runAgent(t, ps.AgentAddr())
621 defer a.Stop()
622 waitForConnectedServerCount(t, 1, a)
623
624 conn, err := net.Dial("unix", ps.FrontAddr())
625 if err != nil {
626 t.Error(err)
627 }
628
629 serverURL, _ := url.Parse(server.URL)
630
631 // Send HTTP-Connect request
632 _, err = fmt.Fprintf(conn, "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n", serverURL.Host, "127.0.0.1")
633 if err != nil {
634 t.Error(err)
635 }
636
637 // Parse the HTTP response for Connect
638 br := bufio.NewReader(conn)
639 res, err := http.ReadResponse(br, nil)
640 if err != nil {
641 t.Errorf("reading HTTP response from CONNECT: %v", err)
642 }
643 if res.StatusCode != 200 {
644 t.Errorf("expect 200; got %d", res.StatusCode)
645 }
646 if br.Buffered() > 0 {
647 t.Error("unexpected extra buffer")
648 }
649
650 dialer := func(_, _ string) (net.Conn, error) {
651 return conn, nil
652 }
653
654 c := &http.Client{
655 Transport: &http.Transport{
656 Dial: dialer,
657 },
658 }
659
660 r, err := c.Get(server.URL)
661 if err != nil {
662 t.Error(err)
663 }
664
665 data, err := io.ReadAll(r.Body)
666 r.Body.Close()
667 if err != nil {
668 t.Error(err)
669 }
670
671 if string(data) != "hello" {
672 t.Errorf("expect %v; got %v", "hello", string(data))
673 }
674
675 }
676
677 func TestFailedDNSLookupProxy_HTTPCONN(t *testing.T) {
678 expectCleanShutdown(t)
679
680 ps := runHTTPConnProxyServer(t)
681 defer ps.Stop()
682
683 a := runAgent(t, ps.AgentAddr())
684 defer a.Stop()
685 waitForConnectedServerCount(t, 1, a)
686
687 conn, err := net.Dial("unix", ps.FrontAddr())
688 if err != nil {
689 t.Error(err)
690 }
691
692 urlString := "http://thissssssxxxxx.com:80"
693 serverURL, _ := url.Parse(urlString)
694
695 // Send HTTP-Connect request
696 _, err = fmt.Fprintf(conn, "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n", serverURL.Host, "127.0.0.1")
697 if err != nil {
698 t.Error(err)
699 }
700
701 // Parse the HTTP response for Connect
702 br := bufio.NewReader(conn)
703 res, err := http.ReadResponse(br, nil)
704 if err != nil {
705 t.Errorf("reading HTTP response from CONNECT: %v", err)
706 }
707
708 if res.StatusCode != 200 {
709 t.Errorf("expect 200; got %d", res.StatusCode)
710 }
711 if br.Buffered() > 0 {
712 t.Error("unexpected extra buffer")
713 }
714 dialer := func(_, _ string) (net.Conn, error) {
715 return conn, nil
716 }
717
718 c := &http.Client{
719 Transport: &http.Transport{
720 Dial: dialer,
721 },
722 }
723
724 resp, err := c.Get(urlString)
725 if err != nil {
726 t.Error(err)
727 }
728
729 if resp.StatusCode != 503 {
730 t.Errorf("expect 503; got %d", res.StatusCode)
731 }
732
733 body, err := io.ReadAll(resp.Body)
734 resp.Body.Close()
735 if !strings.Contains(err.Error(), "connection reset by peer") {
736 t.Error(err)
737 }
738
739 if !strings.Contains(string(body), "no such host") {
740 t.Errorf("Unexpected error: %v", err)
741 }
742
743 if err := ps.Metrics().ExpectServerDialFailure(metricsserver.DialFailureErrorResponse, 1); err != nil {
744 t.Error(err)
745 }
746 if err := a.Metrics().ExpectAgentDialFailure(metricsagent.DialFailureUnknown, 1); err != nil {
747 t.Error(err)
748 }
749 resetAllMetrics() // For clean shutdown.
750 }
751
752 func TestFailedDial_HTTPCONN(t *testing.T) {
753 expectCleanShutdown(t)
754
755 server := httptest.NewServer(newEchoServer("hello"))
756 server.Close() // cleanup immediately so connections will fail
757
758 ps := runHTTPConnProxyServer(t)
759 defer ps.Stop()
760
761 a := runAgent(t, ps.AgentAddr())
762 defer a.Stop()
763 waitForConnectedServerCount(t, 1, a)
764
765 conn, err := net.Dial("unix", ps.FrontAddr())
766 if err != nil {
767 t.Error(err)
768 }
769
770 serverURL, _ := url.Parse(server.URL)
771
772 // Send HTTP-Connect request
773 _, err = fmt.Fprintf(conn, "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n", serverURL.Host, "127.0.0.1")
774 if err != nil {
775 t.Fatal(err)
776 }
777
778 // Parse the HTTP response for Connect
779 br := bufio.NewReader(conn)
780 res, err := http.ReadResponse(br, nil)
781 if err != nil {
782 t.Fatalf("reading HTTP response from CONNECT: %v", err)
783 }
784 if res.StatusCode != 200 {
785 t.Fatalf("expect 200; got %d", res.StatusCode)
786 }
787
788 dialer := func(_, _ string) (net.Conn, error) {
789 return conn, nil
790 }
791
792 c := &http.Client{
793 Transport: &http.Transport{
794 Dial: dialer,
795 },
796 }
797
798 resp, err := c.Get(server.URL)
799 if err != nil {
800 t.Fatal(err)
801 }
802
803 body, err := io.ReadAll(resp.Body)
804 resp.Body.Close()
805 if err == nil {
806 t.Fatalf("Expected error reading response body; response=%q", body)
807 } else if !strings.Contains(err.Error(), "connection reset by peer") {
808 t.Error(err)
809 }
810
811 if !strings.Contains(string(body), "connection refused") {
812 t.Errorf("Unexpected error: %v", err)
813 }
814
815 if err := ps.Metrics().ExpectServerDialFailure(metricsserver.DialFailureErrorResponse, 1); err != nil {
816 t.Error(err)
817 }
818 if err := a.Metrics().ExpectAgentDialFailure(metricsagent.DialFailureUnknown, 1); err != nil {
819 t.Error(err)
820 }
821 resetAllMetrics() // For clean shutdown.
822 }
823
824 func TestProxyHandle_AfterDrain(t *testing.T) {
825 expectCleanShutdown(t)
826
827 server := httptest.NewServer(newEchoServer("hello"))
828 defer server.Close()
829
830 ps := runGRPCProxyServer(t)
831 defer ps.Stop()
832
833 a := runAgent(t, ps.AgentAddr())
834 defer a.Stop()
835 waitForConnectedServerCount(t, 1, a)
836
837 // Drain agent
838 a.Drain()
839
840 ctx, cancel := context.WithCancel(context.Background())
841 defer cancel()
842 tunnel, err := createSingleUseGrpcTunnel(ctx, ps.FrontAddr())
843 if err != nil {
844 t.Fatal(err)
845 }
846
847 c := &http.Client{
848 Transport: &http.Transport{
849 DialContext: tunnel.DialContext,
850 },
851 }
852
853 req, err := http.NewRequest("GET", server.URL, nil)
854 if err != nil {
855 t.Fatal(err)
856 }
857
858 r, err := c.Do(req)
859 if err != nil {
860 t.Fatal(err)
861 }
862 defer r.Body.Close()
863
864 data, err := io.ReadAll(r.Body)
865 if err != nil {
866 t.Fatal(err)
867 }
868 if string(data) != "hello" {
869 t.Errorf("expect %v; got %v", "hello", string(data))
870 }
871 }
872
873 func runGRPCProxyServer(t testing.TB) framework.ProxyServer {
874 return runGRPCProxyServerWithServerCount(t, 1)
875 }
876
877 func runGRPCProxyServerWithServerCount(t testing.TB, serverCount int) framework.ProxyServer {
878 opts := framework.ProxyServerOpts{
879 Mode: server.ModeGRPC,
880 ServerCount: serverCount,
881 }
882 ps, err := Framework.ProxyServerRunner.Start(t, opts)
883 if err != nil {
884 t.Fatalf("Failed to start gRPC proxy server: %v", err)
885 }
886 return ps
887 }
888
889 func runHTTPConnProxyServer(t testing.TB) framework.ProxyServer {
890 opts := framework.ProxyServerOpts{
891 Mode: server.ModeHTTPConnect,
892 ServerCount: 1,
893 }
894 ps, err := Framework.ProxyServerRunner.Start(t, opts)
895 if err != nil {
896 t.Fatalf("Failed to start HTTP proxy server: %v", err)
897 }
898 return ps
899 }
900
901 func runAgent(t testing.TB, addr string) framework.Agent {
902 return runAgentWithID(t, uuid.New().String(), addr)
903 }
904
905 func runAgentWithID(t testing.TB, agentID, addr string) framework.Agent {
906 opts := framework.AgentOpts{
907 AgentID: agentID,
908 ServerAddr: addr,
909 }
910 a, err := Framework.AgentRunner.Start(t, opts)
911 if err != nil {
912 t.Fatalf("Failed to start agent: %v", err)
913 }
914 return a
915 }
916
917 type unresponsiveAgent struct {
918 conn *grpc.ClientConn
919 }
920
921 // Connect registers the unresponsive agent with the proxy server.
922 func (a *unresponsiveAgent) Connect(address string) error {
923 agentID := uuid.New().String()
924 agentCert := filepath.Join(framework.CertsDir, framework.TestAgentCertFile)
925 agentKey := filepath.Join(framework.CertsDir, framework.TestAgentKeyFile)
926 caCert := filepath.Join(framework.CertsDir, framework.TestCAFile)
927 host, _, _ := net.SplitHostPort(address)
928 tlsConfig, err := util.GetClientTLSConfig(caCert, agentCert, agentKey, host, nil)
929 if err != nil {
930 return err
931 }
932 conn, err := grpc.Dial(address, grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)))
933 if err != nil {
934 return err
935 }
936 ctx := metadata.AppendToOutgoingContext(context.Background(),
937 header.AgentID, agentID)
938 _, err = agentproto.NewAgentServiceClient(conn).Connect(ctx)
939 if err != nil {
940 conn.Close()
941 return err
942 }
943
944 a.conn = conn
945 return nil
946 }
947
948 func (a *unresponsiveAgent) Close() {
949 a.conn.Close()
950 }
951
952 // waitForConnectedServerCount waits for the agent ClientSet to have the expected number of health
953 // server connections (HealthyClientsCount).
954 func waitForConnectedServerCount(t testing.TB, expectedServerCount int, a framework.Agent) {
955 t.Helper()
956 startTime := time.Now()
957 lastUpdate := startTime
958 err := wait.PollImmediate(100*time.Millisecond, 5*time.Minute, func() (bool, error) {
959 csc, err := a.GetConnectedServerCount()
960 if err != nil {
961 return false, err
962 }
963 if csc == expectedServerCount {
964 return true, nil
965 }
966 if time.Since(lastUpdate) > 5*time.Second {
967 t.Logf("[%s] Waiting for %d servers, got %d", time.Since(startTime), expectedServerCount, csc)
968 lastUpdate = time.Now()
969 }
970 return false, nil
971 })
972 if err != nil {
973 if csc, err := a.GetConnectedServerCount(); err == nil {
974 t.Logf("got %d server connections; expected %d", csc, expectedServerCount)
975 }
976 t.Fatalf("Error waiting for healthy clients: %v", err)
977 }
978 }
979
980 // waitForConnectedAgentCount waits for the proxy server to have the expected number of registered
981 // agents (backends). This assumes the ProxyServer is using a single ProxyStrategy.
982 func waitForConnectedAgentCount(t testing.TB, expectedAgentCount int, ps framework.ProxyServer) {
983 t.Helper()
984 err := wait.PollImmediate(100*time.Millisecond, framework.ForeverTestTimeout, func() (bool, error) {
985 count, err := ps.ConnectedBackends()
986 if err != nil {
987 return false, err
988 }
989 if count == expectedAgentCount {
990 return true, nil
991 }
992 return false, nil
993 })
994 if err != nil {
995 if count, err := ps.ConnectedBackends(); err == nil {
996 t.Logf("got %d backends; expected %d", count, expectedAgentCount)
997 }
998 t.Fatalf("Error waiting for backend count: %v", err)
999 }
1000 }
1001
1002 func resetAllMetrics() {
1003 metricsclient.Metrics.Reset()
1004 metricsserver.Metrics.Reset()
1005 metricsagent.Metrics.Reset()
1006 }
1007
1008 func expectCleanShutdown(t testing.TB) {
1009 resetAllMetrics()
1010 ignoredGoRoutines := []goleak.Option{
1011 goleak.IgnoreCurrent(),
1012 goleak.IgnoreTopFunction("google.golang.org/grpc.(*addrConn).resetTransport"),
1013 goleak.IgnoreTopFunction("google.golang.org/grpc.(*addrConn).resetTransportAndUnlock"),
1014 }
1015 t.Cleanup(func() {
1016 goleak.VerifyNone(t, ignoredGoRoutines...)
1017 if err := clientmetricstest.ExpectClientDialFailures(nil); err != nil {
1018 t.Errorf("Unexpected %s metric: %v", "dial_failure_total", err)
1019 }
1020
1021 // The following checks are only used with in-process agent/server testing.
1022 if err := metricstest.DefaultTester.ExpectServerDialFailures(nil); err != nil {
1023 t.Errorf("Unexpected %s metric: %v", "dial_failure_count", err)
1024 }
1025 if err := metricstest.DefaultTester.ExpectAgentDialFailures(nil); err != nil {
1026 t.Errorf("Unexpected %s metric: %v", "endpoint_dial_failure_total", err)
1027 }
1028 })
1029 }
1030
1031 func createSingleUseGrpcTunnel(ctx context.Context, addr string) (client.Tunnel, error) {
1032 return client.CreateSingleUseGrpcTunnel(ctx, addr,
1033 grpc.WithContextDialer(
1034 func(ctx context.Context, addr string) (net.Conn, error) {
1035 return (&net.Dialer{}).DialContext(ctx, "unix", addr)
1036 }),
1037 grpc.WithBlock(),
1038 grpc.WithReturnConnectionError(),
1039 grpc.WithTimeout(30*time.Second), // matches http.DefaultTransport dial timeout
1040 grpc.WithTransportCredentials(insecure.NewCredentials()))
1041 }