| 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://thisdefinitelydoesnotexist.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 != 502 { |
| 709 |
t.Errorf("expect 502; got %d", res.StatusCode) |
| 710 |
} |
| 711 |
|
| 712 |
body, err := io.ReadAll(res.Body) |
| 713 |
res.Body.Close() |
| 714 |
|
| 715 |
if !strings.Contains(string(body), "no such host") { |
| 716 |
t.Errorf("Unexpected error: %v", err) |
| 717 |
} |
| 718 |
|
| 719 |
if err := ps.Metrics().ExpectServerDialFailure(metricsserver.DialFailureErrorResponse, 1); err != nil { |
| 720 |
t.Error(err) |
| 721 |
} |
| 722 |
if err := a.Metrics().ExpectAgentDialFailure(metricsagent.DialFailureUnknown, 1); err != nil { |
| 723 |
t.Error(err) |
| 724 |
} |
| 725 |
resetAllMetrics() // For clean shutdown. |
| 726 |
} |
| 727 |
|
| 728 |
func TestFailedDial_HTTPCONN(t *testing.T) { |
| 729 |
expectCleanShutdown(t) |
| 730 |
|
| 731 |
server := httptest.NewServer(newEchoServer("hello")) |
| 732 |
server.Close() // cleanup immediately so connections will fail |
| 733 |
|
| 734 |
ps := runHTTPConnProxyServer(t) |
| 735 |
defer ps.Stop() |
| 736 |
|
| 737 |
a := runAgent(t, ps.AgentAddr()) |
| 738 |
defer a.Stop() |
| 739 |
waitForConnectedServerCount(t, 1, a) |
| 740 |
|
| 741 |
conn, err := net.Dial("unix", ps.FrontAddr()) |
| 742 |
if err != nil { |
| 743 |
t.Error(err) |
| 744 |
} |
| 745 |
|
| 746 |
serverURL, _ := url.Parse(server.URL) |
| 747 |
|
| 748 |
// Send HTTP-Connect request |
| 749 |
_, err = fmt.Fprintf(conn, "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n", serverURL.Host, "127.0.0.1") |
| 750 |
if err != nil { |
| 751 |
t.Fatal(err) |
| 752 |
} |
| 753 |
|
| 754 |
// Parse the HTTP response for Connect |
| 755 |
br := bufio.NewReader(conn) |
| 756 |
res, err := http.ReadResponse(br, nil) |
| 757 |
if err != nil { |
| 758 |
t.Errorf("reading HTTP response from CONNECT: %v", err) |
| 759 |
} |
| 760 |
|
| 761 |
if res.StatusCode != 502 { |
| 762 |
t.Errorf("expect 502; got %d", res.StatusCode) |
| 763 |
} |
| 764 |
|
| 765 |
body, err := io.ReadAll(res.Body) |
| 766 |
res.Body.Close() |
| 767 |
if err != nil { |
| 768 |
t.Fatalf("Expected error reading response body; response=%q", body) |
| 769 |
} |
| 770 |
|
| 771 |
if !strings.Contains(string(body), "connection refused") { |
| 772 |
t.Errorf("Expected 'connection refused' in error body, got: %s", string(body)) |
| 773 |
} |
| 774 |
|
| 775 |
if err := ps.Metrics().ExpectServerDialFailure(metricsserver.DialFailureErrorResponse, 1); err != nil { |
| 776 |
t.Error(err) |
| 777 |
} |
| 778 |
if err := a.Metrics().ExpectAgentDialFailure(metricsagent.DialFailureUnknown, 1); err != nil { |
| 779 |
t.Error(err) |
| 780 |
} |
| 781 |
resetAllMetrics() // For clean shutdown. |
| 782 |
} |
| 783 |
|
| 784 |
func TestProxyHandle_AfterDrain(t *testing.T) { |
| 785 |
expectCleanShutdown(t) |
| 786 |
|
| 787 |
server := httptest.NewServer(newEchoServer("hello")) |
| 788 |
defer server.Close() |
| 789 |
|
| 790 |
ps := runGRPCProxyServer(t) |
| 791 |
defer ps.Stop() |
| 792 |
|
| 793 |
a := runAgent(t, ps.AgentAddr()) |
| 794 |
defer a.Stop() |
| 795 |
waitForConnectedServerCount(t, 1, a) |
| 796 |
|
| 797 |
// Drain agent |
| 798 |
a.Drain() |
| 799 |
|
| 800 |
ctx, cancel := context.WithCancel(context.Background()) |
| 801 |
defer cancel() |
| 802 |
tunnel, err := createSingleUseGrpcTunnel(ctx, ps.FrontAddr()) |
| 803 |
if err != nil { |
| 804 |
t.Fatal(err) |
| 805 |
} |
| 806 |
|
| 807 |
c := &http.Client{ |
| 808 |
Transport: &http.Transport{ |
| 809 |
DialContext: tunnel.DialContext, |
| 810 |
}, |
| 811 |
} |
| 812 |
|
| 813 |
req, err := http.NewRequest("GET", server.URL, nil) |
| 814 |
if err != nil { |
| 815 |
t.Fatal(err) |
| 816 |
} |
| 817 |
|
| 818 |
r, err := c.Do(req) |
| 819 |
if err != nil { |
| 820 |
t.Fatal(err) |
| 821 |
} |
| 822 |
defer r.Body.Close() |
| 823 |
|
| 824 |
data, err := io.ReadAll(r.Body) |
| 825 |
if err != nil { |
| 826 |
t.Fatal(err) |
| 827 |
} |
| 828 |
if string(data) != "hello" { |
| 829 |
t.Errorf("expect %v; got %v", "hello", string(data)) |
| 830 |
} |
| 831 |
} |
| 832 |
|
| 833 |
func runGRPCProxyServer(t testing.TB) framework.ProxyServer { |
| 834 |
return runGRPCProxyServerWithServerCount(t, 1) |
| 835 |
} |
| 836 |
|
| 837 |
func runGRPCProxyServerWithServerCount(t testing.TB, serverCount int) framework.ProxyServer { |
| 838 |
opts := framework.ProxyServerOpts{ |
| 839 |
Mode: server.ModeGRPC, |
| 840 |
ServerCount: serverCount, |
| 841 |
} |
| 842 |
ps, err := Framework.ProxyServerRunner.Start(t, opts) |
| 843 |
if err != nil { |
| 844 |
t.Fatalf("Failed to start gRPC proxy server: %v", err) |
| 845 |
} |
| 846 |
return ps |
| 847 |
} |
| 848 |
|
| 849 |
func runHTTPConnProxyServer(t testing.TB) framework.ProxyServer { |
| 850 |
opts := framework.ProxyServerOpts{ |
| 851 |
Mode: server.ModeHTTPConnect, |
| 852 |
ServerCount: 1, |
| 853 |
} |
| 854 |
ps, err := Framework.ProxyServerRunner.Start(t, opts) |
| 855 |
if err != nil { |
| 856 |
t.Fatalf("Failed to start HTTP proxy server: %v", err) |
| 857 |
} |
| 858 |
return ps |
| 859 |
} |
| 860 |
|
| 861 |
func runAgent(t testing.TB, addr string) framework.Agent { |
| 862 |
return runAgentWithID(t, uuid.New().String(), addr) |
| 863 |
} |
| 864 |
|
| 865 |
func runAgentWithID(t testing.TB, agentID, addr string) framework.Agent { |
| 866 |
opts := framework.AgentOpts{ |
| 867 |
AgentID: agentID, |
| 868 |
ServerAddr: addr, |
| 869 |
} |
| 870 |
a, err := Framework.AgentRunner.Start(t, opts) |
| 871 |
if err != nil { |
| 872 |
t.Fatalf("Failed to start agent: %v", err) |
| 873 |
} |
| 874 |
return a |
| 875 |
} |
| 876 |
|
| 877 |
type unresponsiveAgent struct { |
| 878 |
conn *grpc.ClientConn |
| 879 |
} |
| 880 |
|
| 881 |
// Connect registers the unresponsive agent with the proxy server. |
| 882 |
func (a *unresponsiveAgent) Connect(address string) error { |
| 883 |
agentID := uuid.New().String() |
| 884 |
agentCert := filepath.Join(framework.CertsDir, framework.TestAgentCertFile) |
| 885 |
agentKey := filepath.Join(framework.CertsDir, framework.TestAgentKeyFile) |
| 886 |
caCert := filepath.Join(framework.CertsDir, framework.TestCAFile) |
| 887 |
host, _, _ := net.SplitHostPort(address) |
| 888 |
tlsConfig, err := util.GetClientTLSConfig(caCert, agentCert, agentKey, host, nil) |
| 889 |
if err != nil { |
| 890 |
return err |
| 891 |
} |
| 892 |
conn, err := grpc.Dial(address, grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig))) |
| 893 |
if err != nil { |
| 894 |
return err |
| 895 |
} |
| 896 |
ctx := metadata.AppendToOutgoingContext(context.Background(), |
| 897 |
header.AgentID, agentID) |
| 898 |
_, err = agentproto.NewAgentServiceClient(conn).Connect(ctx) |
| 899 |
if err != nil { |
| 900 |
conn.Close() |
| 901 |
return err |
| 902 |
} |
| 903 |
|
| 904 |
a.conn = conn |
| 905 |
return nil |
| 906 |
} |
| 907 |
|
| 908 |
func (a *unresponsiveAgent) Close() { |
| 909 |
a.conn.Close() |
| 910 |
} |
| 911 |
|
| 912 |
// waitForConnectedServerCount waits for the agent ClientSet to have the expected number of health |
| 913 |
// server connections (HealthyClientsCount). |
| 914 |
func waitForConnectedServerCount(t testing.TB, expectedServerCount int, a framework.Agent) { |
| 915 |
t.Helper() |
| 916 |
startTime := time.Now() |
| 917 |
lastUpdate := startTime |
| 918 |
err := wait.PollImmediate(100*time.Millisecond, 5*time.Minute, func() (bool, error) { |
| 919 |
csc, err := a.GetConnectedServerCount() |
| 920 |
if err != nil { |
| 921 |
return false, err |
| 922 |
} |
| 923 |
if csc == expectedServerCount { |
| 924 |
return true, nil |
| 925 |
} |
| 926 |
if time.Since(lastUpdate) > 5*time.Second { |
| 927 |
t.Logf("[%s] Waiting for %d servers, got %d", time.Since(startTime), expectedServerCount, csc) |
| 928 |
lastUpdate = time.Now() |
| 929 |
} |
| 930 |
return false, nil |
| 931 |
}) |
| 932 |
if err != nil { |
| 933 |
if csc, err := a.GetConnectedServerCount(); err == nil { |
| 934 |
t.Logf("got %d server connections; expected %d", csc, expectedServerCount) |
| 935 |
} |
| 936 |
t.Fatalf("Error waiting for healthy clients: %v", err) |
| 937 |
} |
| 938 |
} |
| 939 |
|
| 940 |
// waitForConnectedAgentCount waits for the proxy server to have the expected number of registered |
| 941 |
// agents (backends). This assumes the ProxyServer is using a single ProxyStrategy. |
| 942 |
func waitForConnectedAgentCount(t testing.TB, expectedAgentCount int, ps framework.ProxyServer) { |
| 943 |
t.Helper() |
| 944 |
err := wait.PollImmediate(100*time.Millisecond, framework.ForeverTestTimeout, func() (bool, error) { |
| 945 |
count, err := ps.ConnectedBackends() |
| 946 |
if err != nil { |
| 947 |
return false, err |
| 948 |
} |
| 949 |
if count == expectedAgentCount { |
| 950 |
return true, nil |
| 951 |
} |
| 952 |
return false, nil |
| 953 |
}) |
| 954 |
if err != nil { |
| 955 |
if count, err := ps.ConnectedBackends(); err == nil { |
| 956 |
t.Logf("got %d backends; expected %d", count, expectedAgentCount) |
| 957 |
} |
| 958 |
t.Fatalf("Error waiting for backend count: %v", err) |
| 959 |
} |
| 960 |
} |
| 961 |
|
| 962 |
func resetAllMetrics() { |
| 963 |
metricsclient.Metrics.Reset() |
| 964 |
metricsserver.Metrics.Reset() |
| 965 |
metricsagent.Metrics.Reset() |
| 966 |
} |
| 967 |
|
| 968 |
func expectCleanShutdown(t testing.TB) { |
| 969 |
resetAllMetrics() |
| 970 |
ignoredGoRoutines := []goleak.Option{ |
| 971 |
goleak.IgnoreCurrent(), |
| 972 |
goleak.IgnoreTopFunction("google.golang.org/grpc.(*addrConn).resetTransport"), |
| 973 |
goleak.IgnoreTopFunction("google.golang.org/grpc.(*addrConn).resetTransportAndUnlock"), |
| 974 |
} |
| 975 |
t.Cleanup(func() { |
| 976 |
goleak.VerifyNone(t, ignoredGoRoutines...) |
| 977 |
if err := clientmetricstest.ExpectClientDialFailures(nil); err != nil { |
| 978 |
t.Errorf("Unexpected %s metric: %v", "dial_failure_total", err) |
| 979 |
} |
| 980 |
|
| 981 |
// The following checks are only used with in-process agent/server testing. |
| 982 |
if err := metricstest.DefaultTester.ExpectServerDialFailures(nil); err != nil { |
| 983 |
t.Errorf("Unexpected %s metric: %v", "dial_failure_count", err) |
| 984 |
} |
| 985 |
if err := metricstest.DefaultTester.ExpectAgentDialFailures(nil); err != nil { |
| 986 |
t.Errorf("Unexpected %s metric: %v", "endpoint_dial_failure_total", err) |
| 987 |
} |
| 988 |
}) |
| 989 |
} |
| 990 |
|
| 991 |
func createSingleUseGrpcTunnel(ctx context.Context, addr string) (client.Tunnel, error) { |
| 992 |
return client.CreateSingleUseGrpcTunnel(ctx, addr, |
| 993 |
grpc.WithContextDialer( |
| 994 |
func(ctx context.Context, addr string) (net.Conn, error) { |
| 995 |
return (&net.Dialer{}).DialContext(ctx, "unix", addr) |
| 996 |
}), |
| 997 |
grpc.WithBlock(), |
| 998 |
grpc.WithReturnConnectionError(), |
| 999 |
grpc.WithTimeout(30*time.Second), // matches http.DefaultTransport dial timeout |
| 1000 |
grpc.WithTransportCredentials(insecure.NewCredentials())) |
| 1001 |
} |