| 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 agent |
| 18 | |
| 19 | import ( |
| 20 | "errors" |
| 21 | "fmt" |
| 22 | "net/http" |
| 23 | "net/http/httptest" |
| 24 | "strings" |
| 25 | "testing" |
| 26 | "time" |
| 27 | |
| 28 | "go.uber.org/goleak" |
| 29 | "google.golang.org/grpc" |
| 30 | "k8s.io/apimachinery/pkg/util/wait" |
| 31 | "k8s.io/klog/v2" |
| 32 | "sigs.k8s.io/apiserver-network-proxy/konnectivity-client/proto/client" |
| 33 | "sigs.k8s.io/apiserver-network-proxy/proto/agent" |
| 34 | ) |
| 35 | |
| 36 | func TestServeData_HTTP(t *testing.T) { |
| 37 | var err error |
| 38 | var stream agent.AgentService_ConnectClient |
| 39 | stopCh := make(chan struct{}) |
| 40 | cs := &ClientSet{ |
| 41 | clients: make(map[string]*Client), |
| 42 | stopCh: stopCh, |
| 43 | } |
| 44 | testClient := &Client{ |
| 45 | connManager: newConnectionManager(), |
| 46 | stopCh: stopCh, |
| 47 | cs: cs, |
| 48 | } |
| 49 | testClient.stream, stream = pipe() |
| 50 | |
| 51 | // Start agent |
| 52 | go testClient.Serve() |
| 53 | defer close(stopCh) |
| 54 | |
| 55 | // Start test http server as remote service |
| 56 | expectedBody := "Hello, client" |
| 57 | ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 58 | fmt.Fprint(w, expectedBody) |
| 59 | })) |
| 60 | defer ts.Close() |
| 61 | |
| 62 | // Simulate sending KAS DIAL_REQ to (Agent) Client |
| 63 | dialPacket := newDialPacket("tcp", ts.URL[len("http://"):], 111) |
| 64 | err = stream.Send(dialPacket) |
| 65 | if err != nil { |
| 66 | t.Fatal(err.Error()) |
| 67 | } |
| 68 | |
| 69 | // Expect receiving DIAL_RSP packet from (Agent) Client |
| 70 | pkt, err := stream.Recv() |
| 71 | if err != nil { |
| 72 | t.Fatal(err.Error()) |
| 73 | } |
| 74 | if pkt == nil { |
| 75 | t.Fatal("unexpected nil packet") |
| 76 | } |
| 77 | if pkt.Type != client.PacketType_DIAL_RSP { |
| 78 | t.Errorf("expect PacketType_DIAL_RSP; got %v", pkt.Type) |
| 79 | } |
| 80 | dialRsp := pkt.Payload.(*client.Packet_DialResponse) |
| 81 | connID := dialRsp.DialResponse.ConnectID |
| 82 | if dialRsp.DialResponse.Random != 111 { |
| 83 | t.Errorf("expect random=111; got %v", dialRsp.DialResponse.Random) |
| 84 | } |
| 85 | |
| 86 | // Send Data (HTTP Request) via (Agent) Client to the test http server |
| 87 | dataPacket := newDataPacket(connID, []byte("GET / HTTP/1.1\r\nHost: localhost\r\n\r\n")) |
| 88 | err = stream.Send(dataPacket) |
| 89 | if err != nil { |
| 90 | t.Error(err.Error()) |
| 91 | } |
| 92 | |
| 93 | // Expect receiving http response via (Agent) Client |
| 94 | pkt, _ = stream.Recv() |
| 95 | if pkt == nil { |
| 96 | t.Fatal("unexpected nil packet") |
| 97 | } |
| 98 | if pkt.Type != client.PacketType_DATA { |
| 99 | t.Errorf("expect PacketType_DATA; got %v", pkt.Type) |
| 100 | } |
| 101 | data := pkt.Payload.(*client.Packet_Data).Data.Data |
| 102 | |
| 103 | // Verify response data |
| 104 | // |
| 105 | // HTTP/1.1 200 OK\r\n |
| 106 | // Date: Tue, 07 May 2019 06:44:57 GMT\r\n |
| 107 | // Content-Length: 14\r\n |
| 108 | // Content-Type: text/plain; charset=utf-8\r\n |
| 109 | // \r\n |
| 110 | // Hello, client |
| 111 | headAndBody := strings.Split(string(data), "\r\n") |
| 112 | if body := headAndBody[len(headAndBody)-1]; body != expectedBody { |
| 113 | t.Errorf("expect body %v; got %v", expectedBody, body) |
| 114 | } |
| 115 | |
| 116 | // Force close the test server which will cause remote connection gets droped |
| 117 | ts.Close() |
| 118 | |
| 119 | // Verify receiving CLOSE_RSP |
| 120 | pkt, _ = stream.Recv() |
| 121 | if pkt == nil { |
| 122 | t.Fatal("unexpected nil packet") |
| 123 | } |
| 124 | if pkt.Type != client.PacketType_CLOSE_RSP { |
| 125 | t.Errorf("expect PacketType_CLOSE_RSP; got %v", pkt.Type) |
| 126 | } |
| 127 | closeErr := pkt.Payload.(*client.Packet_CloseResponse).CloseResponse.Error |
| 128 | if closeErr != "" { |
| 129 | t.Errorf("expect nil closeErr; got %v", closeErr) |
| 130 | } |
| 131 | |
| 132 | // Verify internal state is consistent |
| 133 | waitForConnectionDeletion(t, testClient, connID) |
| 134 | } |
| 135 | |
| 136 | func TestClose_Client(t *testing.T) { |
| 137 | var stream agent.AgentService_ConnectClient |
| 138 | stopCh := make(chan struct{}) |
| 139 | cs := &ClientSet{ |
| 140 | clients: make(map[string]*Client), |
| 141 | stopCh: stopCh, |
| 142 | } |
| 143 | testClient := &Client{ |
| 144 | connManager: newConnectionManager(), |
| 145 | stopCh: stopCh, |
| 146 | cs: cs, |
| 147 | } |
| 148 | testClient.stream, stream = pipe() |
| 149 | |
| 150 | // Start agent |
| 151 | go testClient.Serve() |
| 152 | defer close(stopCh) |
| 153 | |
| 154 | // Start test http server as remote service |
| 155 | ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 156 | fmt.Fprint(w, "hello, world") |
| 157 | })) |
| 158 | defer ts.Close() |
| 159 | |
| 160 | // Simulate sending KAS DIAL_REQ to (Agent) Client |
| 161 | dialPacket := newDialPacket("tcp", ts.URL[len("http://"):], 111) |
| 162 | err := stream.Send(dialPacket) |
| 163 | if err != nil { |
| 164 | t.Fatal(err) |
| 165 | } |
| 166 | |
| 167 | // Expect receiving DIAL_RSP packet from (Agent) Client |
| 168 | pkt, _ := stream.Recv() |
| 169 | if pkt == nil { |
| 170 | t.Fatal("unexpected nil packet") |
| 171 | } |
| 172 | if pkt.Type != client.PacketType_DIAL_RSP { |
| 173 | t.Errorf("expect PacketType_DIAL_RSP; got %v", pkt.Type) |
| 174 | } |
| 175 | dialRsp := pkt.Payload.(*client.Packet_DialResponse) |
| 176 | connID := dialRsp.DialResponse.ConnectID |
| 177 | if dialRsp.DialResponse.Random != 111 { |
| 178 | t.Errorf("expect random=111; got %v", dialRsp.DialResponse.Random) |
| 179 | } |
| 180 | |
| 181 | closePacket := newClosePacket(connID) |
| 182 | if err := stream.Send(closePacket); err != nil { |
| 183 | t.Fatal(err) |
| 184 | } |
| 185 | |
| 186 | // Expect receiving close response via (Agent) Client |
| 187 | pkt, _ = stream.Recv() |
| 188 | if pkt == nil { |
| 189 | t.Error("unexpected nil packet") |
| 190 | } |
| 191 | if pkt.Type != client.PacketType_CLOSE_RSP { |
| 192 | t.Errorf("expect PacketType_CLOSE_RSP; got %v", pkt.Type) |
| 193 | } |
| 194 | closeErr := pkt.Payload.(*client.Packet_CloseResponse).CloseResponse.Error |
| 195 | if closeErr != "" { |
| 196 | t.Errorf("expect nil closeErr; got %v", closeErr) |
| 197 | } |
| 198 | |
| 199 | // Verify internal state is consistent |
| 200 | // connID will be removed when remoteToProxy on another goroutine exits. |
| 201 | // Wait a short period to see if the connection gets cleaned up. |
| 202 | waitForConnectionDeletion(t, testClient, connID) |
| 203 | |
| 204 | // Verify remote conn is closed |
| 205 | if err := stream.Send(closePacket); err != nil { |
| 206 | t.Fatal(err) |
| 207 | } |
| 208 | |
| 209 | // Expect receiving close response via (Agent) Client |
| 210 | pkt, _ = stream.Recv() |
| 211 | if pkt == nil { |
| 212 | t.Error("unexpected nil packet") |
| 213 | } |
| 214 | if pkt.Type != client.PacketType_CLOSE_RSP { |
| 215 | t.Errorf("expect PacketType_CLOSE_RSP; got %+v", pkt) |
| 216 | } |
| 217 | closeErr = pkt.Payload.(*client.Packet_CloseResponse).CloseResponse.Error |
| 218 | if closeErr != "Unknown connectID" { |
| 219 | t.Errorf("expect Unknown connectID; got %v", closeErr) |
| 220 | } |
| 221 | |
| 222 | } |
| 223 | |
| 224 | func TestConnectionMismatch(t *testing.T) { |
| 225 | var stream agent.AgentService_ConnectClient |
| 226 | stopCh := make(chan struct{}) |
| 227 | cs := &ClientSet{ |
| 228 | clients: make(map[string]*Client), |
| 229 | stopCh: stopCh, |
| 230 | } |
| 231 | testClient := &Client{ |
| 232 | connManager: newConnectionManager(), |
| 233 | stopCh: stopCh, |
| 234 | cs: cs, |
| 235 | } |
| 236 | testClient.stream, stream = pipe() |
| 237 | |
| 238 | // Start agent |
| 239 | go testClient.Serve() |
| 240 | defer close(stopCh) |
| 241 | |
| 242 | // Simulate sending a DATA packet to (Agent) Client |
| 243 | const connID = 12345 |
| 244 | pkt := newDataPacket(connID, []byte("hello world")) |
| 245 | if err := stream.Send(pkt); err != nil { |
| 246 | t.Fatal(err) |
| 247 | } |
| 248 | |
| 249 | // Expect to receive CLOSE_RSP packet from (Agent) Client |
| 250 | pkt, err := stream.Recv() |
| 251 | if err != nil { |
| 252 | t.Fatal(err) |
| 253 | } |
| 254 | if pkt.Type != client.PacketType_CLOSE_RSP { |
| 255 | t.Errorf("expect PacketType_CLOSE_RSP; got %v", pkt.Type) |
| 256 | } |
| 257 | closeRsp := pkt.Payload.(*client.Packet_CloseResponse).CloseResponse |
| 258 | if closeRsp.ConnectID != connID { |
| 259 | t.Errorf("expect connID=%d; got %v", connID, closeRsp.ConnectID) |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | // brokenStream wraps a ConnectClient and returns an error on Send and/or Recv if the respective |
| 264 | // error is non-nil. |
| 265 | type brokenStream struct { |
| 266 | agent.AgentService_ConnectClient |
| 267 | |
| 268 | sendErr, recvErr error |
| 269 | } |
| 270 | |
| 271 | func (bs *brokenStream) Send(packet *client.Packet) error { |
| 272 | if bs.sendErr != nil { |
| 273 | return bs.sendErr |
| 274 | } |
| 275 | return bs.AgentService_ConnectClient.Send(packet) |
| 276 | } |
| 277 | |
| 278 | func (bs *brokenStream) Recv() (*client.Packet, error) { |
| 279 | if bs.recvErr != nil { |
| 280 | return nil, bs.recvErr |
| 281 | } |
| 282 | return bs.AgentService_ConnectClient.Recv() |
| 283 | } |
| 284 | |
| 285 | func TestFailedSend_DialResp_GRPC(t *testing.T) { |
| 286 | defer goleakVerifyNone(t, goleak.IgnoreCurrent()) |
| 287 | |
| 288 | stopCh := make(chan struct{}) |
| 289 | cs := &ClientSet{ |
| 290 | clients: make(map[string]*Client), |
| 291 | stopCh: stopCh, |
| 292 | } |
| 293 | testClient := &Client{ |
| 294 | connManager: newConnectionManager(), |
| 295 | stopCh: stopCh, |
| 296 | cs: cs, |
| 297 | } |
| 298 | defer func() { |
| 299 | close(stopCh) |
| 300 | // Give a.probe() time to clean up |
| 301 | // This is terrible and racy |
| 302 | time.Sleep(time.Second) |
| 303 | }() |
| 304 | |
| 305 | clientStream, stream := pipe() |
| 306 | testClient.stream = &brokenStream{ |
| 307 | AgentService_ConnectClient: clientStream, |
| 308 | sendErr: errors.New("expected send error"), |
| 309 | } |
| 310 | |
| 311 | // Start agent |
| 312 | go testClient.Serve() |
| 313 | |
| 314 | // Start test http server as remote service |
| 315 | ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 316 | t.Log("Request Received", "url", r.URL, "userAgent", r.UserAgent()) |
| 317 | fmt.Fprint(w, "hello, world") |
| 318 | })) |
| 319 | defer ts.Close() |
| 320 | |
| 321 | func() { |
| 322 | // goleak.IgnoreCurrent() needs to include all the goroutines which were started by testClient.Serve() above. |
| 323 | // That includes things like pkg/agent/client.go:614 +0x88. Sleep does not guarantee they will have started. |
| 324 | time.Sleep(time.Second) |
| 325 | defer goleakVerifyNone(t, goleak.IgnoreCurrent()) |
| 326 | |
| 327 | // Simulate sending KAS DIAL_REQ to (Agent) Client |
| 328 | dialPacket := newDialPacket("tcp", strings.TrimPrefix(ts.URL, "http://"), 111) |
| 329 | err := stream.Send(dialPacket) |
| 330 | if err != nil { |
| 331 | t.Fatal(err) |
| 332 | } |
| 333 | |
| 334 | // Expect receiving DIAL_RSP packet from (Agent) Client |
| 335 | _, err = stream.Recv() |
| 336 | if err == nil { |
| 337 | t.Error("expected timeout error, got none") |
| 338 | } |
| 339 | |
| 340 | if conns := len(testClient.connManager.List()); conns > 0 { |
| 341 | t.Errorf("Leaked %d connections", conns) |
| 342 | } |
| 343 | }() |
| 344 | } |
| 345 | |
| 346 | func TestDrain(t *testing.T) { |
| 347 | var stream agent.AgentService_ConnectClient |
| 348 | drainCh := make(chan struct{}) |
| 349 | stopCh := make(chan struct{}) |
| 350 | cs := &ClientSet{ |
| 351 | clients: make(map[string]*Client), |
| 352 | drainCh: drainCh, |
| 353 | stopCh: stopCh, |
| 354 | } |
| 355 | testClient := &Client{ |
| 356 | connManager: newConnectionManager(), |
| 357 | drainCh: drainCh, |
| 358 | stopCh: stopCh, |
| 359 | cs: cs, |
| 360 | } |
| 361 | testClient.stream, stream = pipe() |
| 362 | |
| 363 | // Start agent |
| 364 | go testClient.Serve() |
| 365 | defer close(stopCh) |
| 366 | |
| 367 | // Simulate pod first shutdown signal |
| 368 | close(drainCh) |
| 369 | |
| 370 | // Expect to receive DRAIN packet from (Agent) Client |
| 371 | pkt, err := stream.Recv() |
| 372 | if err != nil { |
| 373 | t.Fatal(err) |
| 374 | } |
| 375 | if pkt.Type != client.PacketType_DRAIN { |
| 376 | t.Errorf("expect PacketType_DRAIN; got %v", pkt.Type) |
| 377 | } |
| 378 | } |
| 379 | |
| 380 | // fakeStream implements AgentService_ConnectClient |
| 381 | type fakeStream struct { |
| 382 | grpc.ClientStream |
| 383 | r <-chan *client.Packet |
| 384 | w chan<- *client.Packet |
| 385 | } |
| 386 | |
| 387 | func pipe() (agent.AgentService_ConnectClient, agent.AgentService_ConnectClient) { |
| 388 | r, w := make(chan *client.Packet, 2), make(chan *client.Packet, 2) |
| 389 | s1, s2 := &fakeStream{}, &fakeStream{} |
| 390 | s1.r, s1.w = r, w |
| 391 | s2.r, s2.w = w, r |
| 392 | return s1, s2 |
| 393 | } |
| 394 | |
| 395 | func (s *fakeStream) Send(packet *client.Packet) error { |
| 396 | klog.V(4).InfoS("[DEBUG] send", "packet", packet) |
| 397 | s.w <- packet |
| 398 | return nil |
| 399 | } |
| 400 | |
| 401 | func (s *fakeStream) Recv() (*client.Packet, error) { |
| 402 | select { |
| 403 | case pkt := <-s.r: |
| 404 | klog.V(4).InfoS("[DEBUG] recv", "packet", pkt) |
| 405 | return pkt, nil |
| 406 | case <-time.After(5 * time.Second): |
| 407 | return nil, errors.New("timeout recv") |
| 408 | } |
| 409 | } |
| 410 | |
| 411 | func newDialPacket(protocol, address string, random int64) *client.Packet { |
| 412 | return &client.Packet{ |
| 413 | Type: client.PacketType_DIAL_REQ, |
| 414 | Payload: &client.Packet_DialRequest{ |
| 415 | DialRequest: &client.DialRequest{ |
| 416 | Protocol: protocol, |
| 417 | Address: address, |
| 418 | Random: random, |
| 419 | }, |
| 420 | }, |
| 421 | } |
| 422 | } |
| 423 | |
| 424 | func newDataPacket(connID int64, data []byte) *client.Packet { |
| 425 | return &client.Packet{ |
| 426 | Type: client.PacketType_DATA, |
| 427 | Payload: &client.Packet_Data{ |
| 428 | Data: &client.Data{ |
| 429 | ConnectID: connID, |
| 430 | Data: data, |
| 431 | }, |
| 432 | }, |
| 433 | } |
| 434 | } |
| 435 | |
| 436 | func newClosePacket(connID int64) *client.Packet { |
| 437 | return &client.Packet{ |
| 438 | Type: client.PacketType_CLOSE_REQ, |
| 439 | Payload: &client.Packet_CloseRequest{ |
| 440 | CloseRequest: &client.CloseRequest{ |
| 441 | ConnectID: connID, |
| 442 | }, |
| 443 | }, |
| 444 | } |
| 445 | } |
| 446 | |
| 447 | func waitForConnectionDeletion(t *testing.T, testClient *Client, connID int64) { |
| 448 | t.Helper() |
| 449 | err := wait.PollImmediate(100*time.Millisecond, 3*time.Second, func() (bool, error) { |
| 450 | _, ok := testClient.connManager.Get(connID) |
| 451 | return !ok, nil |
| 452 | }) |
| 453 | if err != nil { |
| 454 | t.Error("client.endpointConn not released") |
| 455 | } |
| 456 | } |
| 457 | |
| 458 | func goleakVerifyNone(t *testing.T, options ...goleak.Option) { |
| 459 | t.Helper() |
| 460 | var err error |
| 461 | waitErr := wait.PollImmediate(100*time.Millisecond, 3*time.Second, func() (bool, error) { |
| 462 | err = goleak.Find(options...) |
| 463 | if err == nil { |
| 464 | return true, nil |
| 465 | } |
| 466 | return false, nil |
| 467 | }) |
| 468 | if waitErr != nil { |
| 469 | t.Error(err) |
| 470 | } |
| 471 | } |