| 1 |
/* |
| 2 |
Copyright 2019 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 server |
| 18 |
|
| 19 |
import ( |
| 20 |
"bufio" |
| 21 |
"context" |
| 22 |
"fmt" |
| 23 |
"io" |
| 24 |
"net" |
| 25 |
"net/http" |
| 26 |
"net/http/httptest" |
| 27 |
"net/url" |
| 28 |
"reflect" |
| 29 |
"sync" |
| 30 |
"testing" |
| 31 |
"time" |
| 32 |
|
| 33 |
"github.com/google/uuid" |
| 34 |
"go.uber.org/mock/gomock" |
| 35 |
"google.golang.org/grpc/metadata" |
| 36 |
|
| 37 |
promtest "github.com/prometheus/client_golang/prometheus/testutil" |
| 38 |
authv1 "k8s.io/api/authentication/v1" |
| 39 |
"k8s.io/apimachinery/pkg/runtime" |
| 40 |
"k8s.io/apimachinery/pkg/util/wait" |
| 41 |
k8sfake "k8s.io/client-go/kubernetes/fake" |
| 42 |
fakeauthenticationv1 "k8s.io/client-go/kubernetes/typed/authentication/v1/fake" |
| 43 |
k8stesting "k8s.io/client-go/testing" |
| 44 |
|
| 45 |
client "sigs.k8s.io/apiserver-network-proxy/konnectivity-client/proto/client" |
| 46 |
"sigs.k8s.io/apiserver-network-proxy/pkg/server/metrics" |
| 47 |
"sigs.k8s.io/apiserver-network-proxy/pkg/server/proxystrategies" |
| 48 |
metricstest "sigs.k8s.io/apiserver-network-proxy/pkg/testing/metrics" |
| 49 |
agentmock "sigs.k8s.io/apiserver-network-proxy/proto/agent/mocks" |
| 50 |
"sigs.k8s.io/apiserver-network-proxy/proto/header" |
| 51 |
) |
| 52 |
|
| 53 |
const xfrChannelSize = 10 |
| 54 |
|
| 55 |
func TestAgentTokenAuthenticationErrorsToken(t *testing.T) { |
| 56 |
stub := gomock.NewController(t) |
| 57 |
defer stub.Finish() |
| 58 |
|
| 59 |
ns := "test_ns" |
| 60 |
sa := "test_sa" |
| 61 |
|
| 62 |
testCases := []struct { |
| 63 |
desc string |
| 64 |
mdKey string |
| 65 |
tokens []string |
| 66 |
wantNamespace string |
| 67 |
wantServiceAccount string |
| 68 |
authenticated bool |
| 69 |
authError string |
| 70 |
tokenReviewError error |
| 71 |
wantError bool |
| 72 |
}{ |
| 73 |
{ |
| 74 |
desc: "no context", |
| 75 |
wantError: true, |
| 76 |
}, |
| 77 |
{ |
| 78 |
desc: "non valid metadata key", |
| 79 |
mdKey: "someKey", |
| 80 |
tokens: []string{"token1"}, |
| 81 |
wantError: true, |
| 82 |
}, |
| 83 |
{ |
| 84 |
desc: "non valid token prefix", |
| 85 |
mdKey: header.AuthenticationTokenContextKey, |
| 86 |
tokens: []string{"token1"}, |
| 87 |
wantError: true, |
| 88 |
}, |
| 89 |
{ |
| 90 |
desc: "multiple valid tokens", |
| 91 |
mdKey: header.AuthenticationTokenContextKey, |
| 92 |
tokens: []string{header.AuthenticationTokenContextSchemePrefix + "token1", header.AuthenticationTokenContextSchemePrefix + "token2"}, |
| 93 |
wantError: true, |
| 94 |
}, |
| 95 |
{ |
| 96 |
desc: "not authenticated", |
| 97 |
authenticated: false, |
| 98 |
mdKey: header.AuthenticationTokenContextKey, |
| 99 |
tokens: []string{header.AuthenticationTokenContextSchemePrefix + "token1"}, |
| 100 |
wantNamespace: ns, |
| 101 |
wantServiceAccount: sa, |
| 102 |
wantError: true, |
| 103 |
}, |
| 104 |
{ |
| 105 |
desc: "tokenReview error", |
| 106 |
authenticated: false, |
| 107 |
mdKey: header.AuthenticationTokenContextKey, |
| 108 |
tokens: []string{header.AuthenticationTokenContextSchemePrefix + "token1"}, |
| 109 |
tokenReviewError: fmt.Errorf("some error"), |
| 110 |
wantNamespace: ns, |
| 111 |
wantServiceAccount: sa, |
| 112 |
wantError: true, |
| 113 |
}, |
| 114 |
{ |
| 115 |
desc: "non valid namespace", |
| 116 |
authenticated: true, |
| 117 |
mdKey: header.AuthenticationTokenContextKey, |
| 118 |
tokens: []string{header.AuthenticationTokenContextSchemePrefix + "token1"}, |
| 119 |
wantNamespace: "_" + ns, |
| 120 |
wantServiceAccount: sa, |
| 121 |
wantError: true, |
| 122 |
}, |
| 123 |
{ |
| 124 |
desc: "non valid service account", |
| 125 |
authenticated: true, |
| 126 |
mdKey: header.AuthenticationTokenContextKey, |
| 127 |
tokens: []string{header.AuthenticationTokenContextSchemePrefix + "token1"}, |
| 128 |
wantNamespace: ns, |
| 129 |
wantServiceAccount: "_" + sa, |
| 130 |
wantError: true, |
| 131 |
}, |
| 132 |
{ |
| 133 |
desc: "authorization succeed", |
| 134 |
authenticated: true, |
| 135 |
mdKey: header.AuthenticationTokenContextKey, |
| 136 |
tokens: []string{header.AuthenticationTokenContextSchemePrefix + "token1"}, |
| 137 |
wantNamespace: ns, |
| 138 |
wantServiceAccount: sa, |
| 139 |
}, |
| 140 |
} |
| 141 |
|
| 142 |
for _, tc := range testCases { |
| 143 |
t.Run(tc.desc, func(t *testing.T) { |
| 144 |
kcs := k8sfake.NewSimpleClientset() |
| 145 |
|
| 146 |
kcs.AuthenticationV1().(*fakeauthenticationv1.FakeAuthenticationV1).Fake.PrependReactor("create", "tokenreviews", func(_ k8stesting.Action) (handled bool, ret runtime.Object, err error) { |
| 147 |
tr := &authv1.TokenReview{ |
| 148 |
Status: authv1.TokenReviewStatus{ |
| 149 |
Authenticated: tc.authenticated, |
| 150 |
Error: tc.authError, |
| 151 |
User: authv1.UserInfo{ |
| 152 |
Username: fmt.Sprintf("system:serviceaccount:%v:%v", ns, sa), |
| 153 |
}, |
| 154 |
}, |
| 155 |
} |
| 156 |
return true, tr, tc.tokenReviewError |
| 157 |
}) |
| 158 |
|
| 159 |
var md metadata.MD |
| 160 |
for _, token := range tc.tokens { |
| 161 |
md = metadata.Join(md, metadata.Pairs(tc.mdKey, token)) |
| 162 |
} |
| 163 |
|
| 164 |
md = metadata.Join(md, metadata.Pairs(header.AgentID, "")) |
| 165 |
|
| 166 |
ctx := context.Background() |
| 167 |
defer ctx.Done() |
| 168 |
ctx = metadata.NewIncomingContext(ctx, md) |
| 169 |
conn := agentmock.NewMockAgentService_ConnectServer(stub) |
| 170 |
conn.EXPECT().Context().AnyTimes().Return(ctx) |
| 171 |
|
| 172 |
// close agent's connection if no error is expected |
| 173 |
if !tc.wantError { |
| 174 |
conn.EXPECT().SendHeader(gomock.Any()).Return(nil) |
| 175 |
conn.EXPECT().Recv().Return(nil, io.EOF) |
| 176 |
} |
| 177 |
|
| 178 |
p := NewProxyServer("", []proxystrategies.ProxyStrategy{proxystrategies.ProxyStrategyDefault}, 1, &AgentTokenAuthenticationOptions{ |
| 179 |
Enabled: true, |
| 180 |
KubernetesClient: kcs, |
| 181 |
AgentNamespace: tc.wantNamespace, |
| 182 |
AgentServiceAccount: tc.wantServiceAccount, |
| 183 |
}, xfrChannelSize) |
| 184 |
|
| 185 |
err := p.Connect(conn) |
| 186 |
if tc.wantError { |
| 187 |
if err == nil { |
| 188 |
t.Errorf("test case expected for error") |
| 189 |
} |
| 190 |
} else { |
| 191 |
if err != nil { |
| 192 |
t.Errorf("did not expected for error but got :%v", err) |
| 193 |
} |
| 194 |
} |
| 195 |
}) |
| 196 |
} |
| 197 |
} |
| 198 |
|
| 199 |
func TestRemovePendingDialForStream(t *testing.T) { |
| 200 |
streamUID := "target-uuid" |
| 201 |
pending1 := &ProxyClientConnection{frontend: &GrpcFrontend{streamUID: streamUID}} |
| 202 |
pending2 := &ProxyClientConnection{} |
| 203 |
pending3 := &ProxyClientConnection{frontend: &GrpcFrontend{streamUID: streamUID}} |
| 204 |
pending4 := &ProxyClientConnection{frontend: &GrpcFrontend{streamUID: "different-uid"}} |
| 205 |
pending5 := &ProxyClientConnection{frontend: &GrpcFrontend{streamUID: ""}} |
| 206 |
p := NewProxyServer("", []proxystrategies.ProxyStrategy{proxystrategies.ProxyStrategyDefault}, 1, nil, xfrChannelSize) |
| 207 |
p.PendingDial.Add(1, pending1) |
| 208 |
p.PendingDial.Add(2, pending2) |
| 209 |
p.PendingDial.Add(3, pending3) |
| 210 |
p.PendingDial.Add(4, pending4) |
| 211 |
p.PendingDial.Add(5, pending5) |
| 212 |
p.PendingDial.removeForStream(streamUID) |
| 213 |
expectedPending := map[int64]*ProxyClientConnection{ |
| 214 |
int64(2): pending2, |
| 215 |
int64(4): pending4, |
| 216 |
int64(5): pending5, |
| 217 |
} |
| 218 |
if e, a := expectedPending, p.PendingDial.pendingDial; !reflect.DeepEqual(e, a) { |
| 219 |
t.Errorf("expected %v, got %v", e, a) |
| 220 |
} |
| 221 |
p.PendingDial.removeForStream("") |
| 222 |
if e, a := expectedPending, p.PendingDial.pendingDial; !reflect.DeepEqual(e, a) { |
| 223 |
t.Errorf("expected %v, got %v", e, a) |
| 224 |
} |
| 225 |
} |
| 226 |
|
| 227 |
func TestHTTPConnectTunnelBlockedBackendDialSendTimesOutCleansPendingDialAndRetiresBackend(t *testing.T) { |
| 228 |
ctrl := gomock.NewController(t) |
| 229 |
defer ctrl.Finish() |
| 230 |
|
| 231 |
metrics.Metrics.Reset() |
| 232 |
|
| 233 |
proxyServer := NewProxyServer(uuid.New().String(), []proxystrategies.ProxyStrategy{proxystrategies.ProxyStrategyDefault}, 1, &AgentTokenAuthenticationOptions{}, xfrChannelSize) |
| 234 |
proxyServer.SetBackendDialTimeout(500 * time.Millisecond) |
| 235 |
|
| 236 |
agentConn, backend := prepareAgentConnMD(t, ctrl, proxyServer, nil) |
| 237 |
sendStarted := make(chan *client.Packet, 1) |
| 238 |
releaseSend := make(chan struct{}) |
| 239 |
sendReleased := make(chan struct{}) |
| 240 |
agentConn.EXPECT().Send(gomock.AssignableToTypeOf(&client.Packet{})).DoAndReturn(func(pkt *client.Packet) error { |
| 241 |
sendStarted <- pkt |
| 242 |
<-releaseSend |
| 243 |
close(sendReleased) |
| 244 |
return nil |
| 245 |
}).Times(1) |
| 246 |
|
| 247 |
front := httptest.NewServer(&Tunnel{Server: proxyServer}) |
| 248 |
defer front.Close() |
| 249 |
|
| 250 |
frontURL, err := url.Parse(front.URL) |
| 251 |
if err != nil { |
| 252 |
t.Fatalf("failed to parse front URL: %v", err) |
| 253 |
} |
| 254 |
conn, err := net.Dial("tcp", frontURL.Host) |
| 255 |
if err != nil { |
| 256 |
t.Fatalf("failed to connect to HTTP CONNECT front: %v", err) |
| 257 |
} |
| 258 |
defer conn.Close() |
| 259 |
|
| 260 |
if _, err := fmt.Fprintf(conn, "CONNECT 127.0.0.1:443 HTTP/1.1\r\nHost: 127.0.0.1:443\r\n\r\n"); err != nil { |
| 261 |
t.Fatalf("failed to write CONNECT request: %v", err) |
| 262 |
} |
| 263 |
|
| 264 |
var sent *client.Packet |
| 265 |
select { |
| 266 |
case sent = <-sendStarted: |
| 267 |
case <-time.After(time.Second): |
| 268 |
t.Fatal("timed out waiting for backend DIAL_REQ send to start") |
| 269 |
} |
| 270 |
if sent.Type != client.PacketType_DIAL_REQ { |
| 271 |
t.Fatalf("expected DIAL_REQ to backend, got %v", sent.Type) |
| 272 |
} |
| 273 |
if got := pendingDialCount(proxyServer); got != 1 { |
| 274 |
t.Fatalf("expected one pending dial while backend Send is blocked, got %d", got) |
| 275 |
} |
| 276 |
|
| 277 |
respCh := make(chan struct { |
| 278 |
resp *http.Response |
| 279 |
err error |
| 280 |
}, 1) |
| 281 |
go func() { |
| 282 |
resp, err := http.ReadResponse(bufio.NewReader(conn), nil) |
| 283 |
respCh <- struct { |
| 284 |
resp *http.Response |
| 285 |
err error |
| 286 |
}{resp: resp, err: err} |
| 287 |
}() |
| 288 |
|
| 289 |
var resp *http.Response |
| 290 |
select { |
| 291 |
case got := <-respCh: |
| 292 |
if got.err != nil { |
| 293 |
t.Fatalf("failed to read CONNECT response: %v", got.err) |
| 294 |
} |
| 295 |
resp = got.resp |
| 296 |
case <-time.After(2 * time.Second): |
| 297 |
t.Fatal("timed out waiting for backend dial timeout response") |
| 298 |
} |
| 299 |
defer resp.Body.Close() |
| 300 |
|
| 301 |
if resp.StatusCode != http.StatusGatewayTimeout { |
| 302 |
t.Fatalf("expected %d for blocked backend dial send, got %s", http.StatusGatewayTimeout, resp.Status) |
| 303 |
} |
| 304 |
if got := pendingDialCount(proxyServer); got != 0 { |
| 305 |
t.Fatalf("expected pending dial to be cleaned after backend dial timeout, got %d", got) |
| 306 |
} |
| 307 |
if !backend.IsDraining() { |
| 308 |
t.Fatal("expected backend to be marked draining after backend dial timeout") |
| 309 |
} |
| 310 |
select { |
| 311 |
case <-backend.Done(): |
| 312 |
case <-time.After(time.Second): |
| 313 |
t.Fatal("expected backend retire signal after backend dial timeout") |
| 314 |
} |
| 315 |
for _, bm := range proxyServer.BackendManagers { |
| 316 |
if got := bm.NumBackends(); got != 0 { |
| 317 |
t.Fatalf("expected timed-out backend to be retired from manager, got %d backends", got) |
| 318 |
} |
| 319 |
} |
| 320 |
|
| 321 |
close(releaseSend) |
| 322 |
select { |
| 323 |
case <-sendReleased: |
| 324 |
case <-time.After(time.Second): |
| 325 |
t.Fatal("timed out waiting for blocked backend Send goroutine to exit") |
| 326 |
} |
| 327 |
} |
| 328 |
|
| 329 |
func TestAddRemoveFrontends(t *testing.T) { |
| 330 |
agent1ConnID1 := new(ProxyClientConnection) |
| 331 |
agent1ConnID2 := new(ProxyClientConnection) |
| 332 |
agent2ConnID1 := new(ProxyClientConnection) |
| 333 |
agent2ConnID2 := new(ProxyClientConnection) |
| 334 |
agent3ConnID1 := new(ProxyClientConnection) |
| 335 |
|
| 336 |
p := NewProxyServer("", []proxystrategies.ProxyStrategy{proxystrategies.ProxyStrategyDefault}, 1, nil, xfrChannelSize) |
| 337 |
p.addEstablished("agent1", int64(1), agent1ConnID1) |
| 338 |
p.removeEstablished("agent1", int64(1)) |
| 339 |
expectedFrontends := make(map[string]map[int64]*ProxyClientConnection) |
| 340 |
if e, a := expectedFrontends, p.established; !reflect.DeepEqual(e, a) { |
| 341 |
t.Errorf("expected %v, got %v", e, a) |
| 342 |
} |
| 343 |
|
| 344 |
p = NewProxyServer("", []proxystrategies.ProxyStrategy{proxystrategies.ProxyStrategyDefault}, 1, nil, xfrChannelSize) |
| 345 |
p.addEstablished("agent1", int64(1), agent1ConnID1) |
| 346 |
p.addEstablished("agent1", int64(2), agent1ConnID2) |
| 347 |
p.addEstablished("agent2", int64(1), agent2ConnID1) |
| 348 |
p.addEstablished("agent2", int64(2), agent2ConnID2) |
| 349 |
p.addEstablished("agent3", int64(1), agent3ConnID1) |
| 350 |
p.removeEstablished("agent2", int64(1)) |
| 351 |
p.removeEstablished("agent2", int64(2)) |
| 352 |
p.removeEstablished("agent1", int64(1)) |
| 353 |
expectedFrontends = map[string]map[int64]*ProxyClientConnection{ |
| 354 |
"agent1": { |
| 355 |
int64(2): agent1ConnID2, |
| 356 |
}, |
| 357 |
"agent3": { |
| 358 |
int64(1): agent3ConnID1, |
| 359 |
}, |
| 360 |
} |
| 361 |
if e, a := expectedFrontends, p.established; !reflect.DeepEqual(e, a) { |
| 362 |
t.Errorf("expected %v, got %v", e, a) |
| 363 |
} |
| 364 |
} |
| 365 |
|
| 366 |
func TestAddRemoveBackends_DefaultStrategy(t *testing.T) { |
| 367 |
ctrl := gomock.NewController(t) |
| 368 |
defer ctrl.Finish() |
| 369 |
|
| 370 |
backend1, _ := NewBackend(mockAgentConn(ctrl, "agent1", []string{})) |
| 371 |
backend2, _ := NewBackend(mockAgentConn(ctrl, "agent2", []string{})) |
| 372 |
backend3, _ := NewBackend(mockAgentConn(ctrl, "agent3", []string{})) |
| 373 |
|
| 374 |
p := NewProxyServer("", []proxystrategies.ProxyStrategy{proxystrategies.ProxyStrategyDefault}, 1, nil, xfrChannelSize) |
| 375 |
|
| 376 |
p.addBackend(backend1) |
| 377 |
|
| 378 |
if got, _ := p.getBackend("127.0.0.1"); got != backend1 { |
| 379 |
t.Errorf("expected %v, got %v", backend1, got) |
| 380 |
} |
| 381 |
|
| 382 |
p.addBackend(backend2) |
| 383 |
p.addBackend(backend3) |
| 384 |
p.removeBackend(backend1) |
| 385 |
p.removeBackend(backend2) |
| 386 |
|
| 387 |
if got, _ := p.getBackend("127.0.0.1"); got != backend3 { |
| 388 |
t.Errorf("expected %v, got %v", backend3, got) |
| 389 |
} |
| 390 |
|
| 391 |
p.removeBackend(backend3) |
| 392 |
|
| 393 |
if got, _ := p.getBackend("127.0.0.1"); got != nil { |
| 394 |
t.Errorf("expected nil, got %v", got) |
| 395 |
} |
| 396 |
} |
| 397 |
|
| 398 |
func TestAddRemoveBackends_DefaultRouteStrategy(t *testing.T) { |
| 399 |
ctrl := gomock.NewController(t) |
| 400 |
defer ctrl.Finish() |
| 401 |
|
| 402 |
backend1, _ := NewBackend(mockAgentConn(ctrl, "agent1", []string{})) |
| 403 |
backend2, _ := NewBackend(mockAgentConn(ctrl, "agent2", []string{"default-route=false"})) |
| 404 |
backend3, _ := NewBackend(mockAgentConn(ctrl, "agent3", []string{"default-route=true"})) |
| 405 |
|
| 406 |
p := NewProxyServer("", []proxystrategies.ProxyStrategy{proxystrategies.ProxyStrategyDefaultRoute}, 1, nil, xfrChannelSize) |
| 407 |
|
| 408 |
p.addBackend(backend1) |
| 409 |
|
| 410 |
if got, _ := p.getBackend("127.0.0.1"); got != nil { |
| 411 |
t.Errorf("expected nil, got %v", got) |
| 412 |
} |
| 413 |
|
| 414 |
p.addBackend(backend2) |
| 415 |
|
| 416 |
if got, _ := p.getBackend("127.0.0.1"); got != nil { |
| 417 |
t.Errorf("expected nil, got %v", got) |
| 418 |
} |
| 419 |
|
| 420 |
p.addBackend(backend3) |
| 421 |
|
| 422 |
if got, _ := p.getBackend("127.0.0.1"); got != backend3 { |
| 423 |
t.Errorf("expected %v, got %v", backend3, got) |
| 424 |
} |
| 425 |
|
| 426 |
p.removeBackend(backend1) |
| 427 |
p.removeBackend(backend2) |
| 428 |
|
| 429 |
if got, _ := p.getBackend("127.0.0.1"); got != backend3 { |
| 430 |
t.Errorf("expected %v, got %v", backend3, got) |
| 431 |
} |
| 432 |
|
| 433 |
p.removeBackend(backend3) |
| 434 |
|
| 435 |
if got, _ := p.getBackend("127.0.0.1"); got != nil { |
| 436 |
t.Errorf("expected nil, got %v", got) |
| 437 |
} |
| 438 |
} |
| 439 |
|
| 440 |
func TestAddRemoveBackends_DestHostStrategy(t *testing.T) { |
| 441 |
ctrl := gomock.NewController(t) |
| 442 |
defer ctrl.Finish() |
| 443 |
|
| 444 |
backend1, _ := NewBackend(mockAgentConn(ctrl, "agent1", []string{"host=localhost&host=node1.mydomain.com&ipv4=1.2.3.4&ipv6=9878::7675:1292:9183:7562"})) |
| 445 |
backend2, _ := NewBackend(mockAgentConn(ctrl, "agent2", []string{"default-route=true"})) |
| 446 |
backend3, _ := NewBackend(mockAgentConn(ctrl, "agent3", []string{"host=node2.mydomain.com&ipv4=5.6.7.8&ipv6=::"})) |
| 447 |
|
| 448 |
p := NewProxyServer("", []proxystrategies.ProxyStrategy{proxystrategies.ProxyStrategyDestHost}, 1, nil, xfrChannelSize) |
| 449 |
|
| 450 |
p.addBackend(backend1) |
| 451 |
p.addBackend(backend2) |
| 452 |
p.addBackend(backend3) |
| 453 |
|
| 454 |
if got, _ := p.getBackend("127.0.0.1"); got != nil { |
| 455 |
t.Errorf("expected nil, got %v", got) |
| 456 |
} |
| 457 |
if got, _ := p.getBackend("localhost"); got != backend1 { |
| 458 |
t.Errorf("expected %v, got %v", backend1, got) |
| 459 |
} |
| 460 |
if got, _ := p.getBackend("node1.mydomain.com"); got != backend1 { |
| 461 |
t.Errorf("expected %v, got %v", backend1, got) |
| 462 |
} |
| 463 |
if got, _ := p.getBackend("1.2.3.4"); got != backend1 { |
| 464 |
t.Errorf("expected %v, got %v", backend1, got) |
| 465 |
} |
| 466 |
if got, _ := p.getBackend("9878::7675:1292:9183:7562"); got != backend1 { |
| 467 |
t.Errorf("expected %v, got %v", backend1, got) |
| 468 |
} |
| 469 |
if got, _ := p.getBackend("node2.mydomain.com"); got != backend3 { |
| 470 |
t.Errorf("expected %v, got %v", backend3, got) |
| 471 |
} |
| 472 |
if got, _ := p.getBackend("5.6.7.8"); got != backend3 { |
| 473 |
t.Errorf("expected %v, got %v", backend3, got) |
| 474 |
} |
| 475 |
if got, _ := p.getBackend("::"); got != backend3 { |
| 476 |
t.Errorf("expected %v, got %v", backend3, got) |
| 477 |
} |
| 478 |
|
| 479 |
p.removeBackend(backend1) |
| 480 |
p.removeBackend(backend2) |
| 481 |
p.removeBackend(backend3) |
| 482 |
|
| 483 |
if got, _ := p.getBackend("127.0.0.1"); got != nil { |
| 484 |
t.Errorf("expected nil, got %v", got) |
| 485 |
} |
| 486 |
} |
| 487 |
|
| 488 |
func TestAddRemoveBackends_DestHostSanitizeRequest(t *testing.T) { |
| 489 |
ctrl := gomock.NewController(t) |
| 490 |
defer ctrl.Finish() |
| 491 |
|
| 492 |
backend1, _ := NewBackend(mockAgentConn(ctrl, "agent1", []string{"host=localhost&host=node1.mydomain.com&ipv4=1.2.3.4&ipv6=9878::7675:1292:9183:7562"})) |
| 493 |
backend2, _ := NewBackend(mockAgentConn(ctrl, "agent2", []string{"host=node2.mydomain.com&ipv4=5.6.7.8&ipv6=::"})) |
| 494 |
|
| 495 |
p := NewProxyServer("", []proxystrategies.ProxyStrategy{proxystrategies.ProxyStrategyDestHost}, 1, nil, xfrChannelSize) |
| 496 |
|
| 497 |
p.addBackend(backend1) |
| 498 |
p.addBackend(backend2) |
| 499 |
|
| 500 |
if got, _ := p.getBackend("127.0.0.1:443"); got != nil { |
| 501 |
t.Errorf("expected nil, got %v", got) |
| 502 |
} |
| 503 |
if got, _ := p.getBackend("node1.mydomain.com:443"); got != backend1 { |
| 504 |
t.Errorf("expected %v, got %v", backend1, got) |
| 505 |
} |
| 506 |
if got, _ := p.getBackend("node2.mydomain.com:443"); got != backend2 { |
| 507 |
t.Errorf("expected %v, got %v", backend2, got) |
| 508 |
} |
| 509 |
} |
| 510 |
|
| 511 |
func TestAddRemoveBackends_DestHostWithDefault(t *testing.T) { |
| 512 |
ctrl := gomock.NewController(t) |
| 513 |
defer ctrl.Finish() |
| 514 |
|
| 515 |
backend1, _ := NewBackend(mockAgentConn(ctrl, "agent1", []string{"host=localhost&host=node1.mydomain.com&ipv4=1.2.3.4&ipv6=9878::7675:1292:9183:7562"})) |
| 516 |
backend2, _ := NewBackend(mockAgentConn(ctrl, "agent2", []string{"default-route=false"})) |
| 517 |
backend3, _ := NewBackend(mockAgentConn(ctrl, "agent3", []string{"host=node2.mydomain.com&ipv4=5.6.7.8&ipv6=::"})) |
| 518 |
|
| 519 |
p := NewProxyServer("", []proxystrategies.ProxyStrategy{proxystrategies.ProxyStrategyDestHost, proxystrategies.ProxyStrategyDefault}, 1, nil, xfrChannelSize) |
| 520 |
|
| 521 |
p.addBackend(backend1) |
| 522 |
p.addBackend(backend2) |
| 523 |
p.addBackend(backend3) |
| 524 |
|
| 525 |
if got, _ := p.getBackend("127.0.0.1"); got == nil { |
| 526 |
t.Errorf("expected random fallback, got nil") |
| 527 |
} |
| 528 |
if got, _ := p.getBackend("localhost"); got != backend1 { |
| 529 |
t.Errorf("expected %v, got %v", backend1, got) |
| 530 |
} |
| 531 |
if got, _ := p.getBackend("node1.mydomain.com"); got != backend1 { |
| 532 |
t.Errorf("expected %v, got %v", backend1, got) |
| 533 |
} |
| 534 |
if got, _ := p.getBackend("1.2.3.4"); got != backend1 { |
| 535 |
t.Errorf("expected %v, got %v", backend1, got) |
| 536 |
} |
| 537 |
if got, _ := p.getBackend("9878::7675:1292:9183:7562"); got != backend1 { |
| 538 |
t.Errorf("expected %v, got %v", backend1, got) |
| 539 |
} |
| 540 |
if got, _ := p.getBackend("node2.mydomain.com"); got != backend3 { |
| 541 |
t.Errorf("expected %v, got %v", backend3, got) |
| 542 |
} |
| 543 |
if got, _ := p.getBackend("5.6.7.8"); got != backend3 { |
| 544 |
t.Errorf("expected %v, got %v", backend3, got) |
| 545 |
} |
| 546 |
if got, _ := p.getBackend("::"); got != backend3 { |
| 547 |
t.Errorf("expected %v, got %v", backend3, got) |
| 548 |
} |
| 549 |
|
| 550 |
p.removeBackend(backend1) |
| 551 |
p.removeBackend(backend2) |
| 552 |
|
| 553 |
if got, _ := p.getBackend("127.0.0.1"); got != backend3 { |
| 554 |
t.Errorf("expected %v, got %v", backend3, got) |
| 555 |
} |
| 556 |
|
| 557 |
p.removeBackend(backend3) |
| 558 |
|
| 559 |
if got, _ := p.getBackend("127.0.0.1"); got != nil { |
| 560 |
t.Errorf("expected nil, got %v", got) |
| 561 |
} |
| 562 |
} |
| 563 |
|
| 564 |
func TestAddRemoveBackends_DestHostWithDuplicateIdents(t *testing.T) { |
| 565 |
ctrl := gomock.NewController(t) |
| 566 |
defer ctrl.Finish() |
| 567 |
|
| 568 |
backend1, _ := NewBackend(mockAgentConn(ctrl, "agent1", []string{"host=localhost&host=node1.mydomain.com&ipv4=1.2.3.4&ipv6=9878::7675:1292:9183:7562"})) |
| 569 |
backend2, _ := NewBackend(mockAgentConn(ctrl, "agent2", []string{"host=localhost&host=node1.mydomain.com&ipv4=1.2.3.4&ipv6=9878::7675:1292:9183:7562"})) |
| 570 |
backend3, _ := NewBackend(mockAgentConn(ctrl, "agent3", []string{"host=localhost&host=node2.mydomain.com&ipv4=5.6.7.8&ipv6=::"})) |
| 571 |
|
| 572 |
p := NewProxyServer("", []proxystrategies.ProxyStrategy{proxystrategies.ProxyStrategyDestHost, proxystrategies.ProxyStrategyDefault}, 1, nil, xfrChannelSize) |
| 573 |
|
| 574 |
p.addBackend(backend1) |
| 575 |
p.addBackend(backend2) |
| 576 |
p.addBackend(backend3) |
| 577 |
|
| 578 |
if got, _ := p.getBackend("127.0.0.1"); got == nil { |
| 579 |
t.Errorf("expected random fallback, got nil") |
| 580 |
} |
| 581 |
if got, _ := p.getBackend("localhost"); got == nil { |
| 582 |
t.Errorf("expected any backend, got nil") |
| 583 |
} |
| 584 |
|
| 585 |
p.removeBackend(backend1) |
| 586 |
p.removeBackend(backend3) |
| 587 |
|
| 588 |
if got, _ := p.getBackend("127.0.0.1"); got != backend2 { |
| 589 |
t.Errorf("expected %v, got %v", backend2, got) |
| 590 |
} |
| 591 |
if got, _ := p.getBackend("localhost"); got != backend2 { |
| 592 |
t.Errorf("expected %v, got %v", backend2, got) |
| 593 |
} |
| 594 |
if got, _ := p.getBackend("node1.mydomain.com"); got != backend2 { |
| 595 |
t.Errorf("expected %v, got %v", backend2, got) |
| 596 |
} |
| 597 |
if got, _ := p.getBackend("1.2.3.4"); got != backend2 { |
| 598 |
t.Errorf("expected %v, got %v", backend2, got) |
| 599 |
} |
| 600 |
if got, _ := p.getBackend("9878::7675:1292:9183:7562"); got != backend2 { |
| 601 |
t.Errorf("expected %v, got %v", backend2, got) |
| 602 |
} |
| 603 |
if got, _ := p.getBackend("node2.mydomain.com"); got != backend2 { |
| 604 |
t.Errorf("expected %v, got %v", backend2, got) |
| 605 |
} |
| 606 |
if got, _ := p.getBackend("5.6.7.8"); got != backend2 { |
| 607 |
t.Errorf("expected %v, got %v", backend2, got) |
| 608 |
} |
| 609 |
if got, _ := p.getBackend("::"); got != backend2 { |
| 610 |
t.Errorf("expected %v, got %v", backend2, got) |
| 611 |
} |
| 612 |
|
| 613 |
p.removeBackend(backend2) |
| 614 |
|
| 615 |
if got, _ := p.getBackend("127.0.0.1"); got != nil { |
| 616 |
t.Errorf("expected nil, got %v", got) |
| 617 |
} |
| 618 |
} |
| 619 |
|
| 620 |
func TestEstablishedConnsMetric(t *testing.T) { |
| 621 |
metrics.Metrics.Reset() |
| 622 |
|
| 623 |
agent1ConnID1 := new(ProxyClientConnection) |
| 624 |
agent1ConnID2 := new(ProxyClientConnection) |
| 625 |
agent2ConnID1 := new(ProxyClientConnection) |
| 626 |
agent2ConnID2 := new(ProxyClientConnection) |
| 627 |
agent3ConnID1 := new(ProxyClientConnection) |
| 628 |
|
| 629 |
p := NewProxyServer("", []proxystrategies.ProxyStrategy{proxystrategies.ProxyStrategyDefault}, 1, nil, xfrChannelSize) |
| 630 |
p.addEstablished("agent1", int64(1), agent1ConnID1) |
| 631 |
assertEstablishedConnsMetric(t, 1) |
| 632 |
p.addEstablished("agent1", int64(2), agent1ConnID2) |
| 633 |
assertEstablishedConnsMetric(t, 2) |
| 634 |
p.addEstablished("agent2", int64(1), agent2ConnID1) |
| 635 |
assertEstablishedConnsMetric(t, 3) |
| 636 |
p.addEstablished("agent2", int64(2), agent2ConnID2) |
| 637 |
assertEstablishedConnsMetric(t, 4) |
| 638 |
p.addEstablished("agent3", int64(1), agent3ConnID1) |
| 639 |
assertEstablishedConnsMetric(t, 5) |
| 640 |
p.removeEstablished("agent2", int64(1)) |
| 641 |
assertEstablishedConnsMetric(t, 4) |
| 642 |
p.removeEstablished("agent2", int64(2)) |
| 643 |
assertEstablishedConnsMetric(t, 3) |
| 644 |
p.removeEstablished("agent1", int64(1)) |
| 645 |
assertEstablishedConnsMetric(t, 2) |
| 646 |
p.removeEstablished("agent1", int64(2)) |
| 647 |
assertEstablishedConnsMetric(t, 1) |
| 648 |
p.removeEstablished("agent3", int64(1)) |
| 649 |
assertEstablishedConnsMetric(t, 0) |
| 650 |
} |
| 651 |
|
| 652 |
func TestRemoveEstablishedForBackendConn(t *testing.T) { |
| 653 |
backend1 := &Backend{} |
| 654 |
backend2 := &Backend{} |
| 655 |
backend3 := &Backend{} |
| 656 |
agent1ConnID1 := &ProxyClientConnection{backend: backend1} |
| 657 |
agent1ConnID2 := &ProxyClientConnection{backend: backend1} |
| 658 |
agent2ConnID1 := &ProxyClientConnection{backend: backend2} |
| 659 |
agent2ConnID2 := &ProxyClientConnection{backend: backend2} |
| 660 |
agent3ConnID1 := &ProxyClientConnection{backend: backend3} |
| 661 |
p := NewProxyServer("", []proxystrategies.ProxyStrategy{proxystrategies.ProxyStrategyDefault}, 1, nil, xfrChannelSize) |
| 662 |
p.addEstablished("agent1", int64(1), agent1ConnID1) |
| 663 |
p.addEstablished("agent1", int64(2), agent1ConnID2) |
| 664 |
p.addEstablished("agent2", int64(1), agent2ConnID1) |
| 665 |
p.addEstablished("agent2", int64(2), agent2ConnID2) |
| 666 |
p.addEstablished("agent3", int64(1), agent3ConnID1) |
| 667 |
p.removeEstablishedForBackendConn("agent2", backend2) |
| 668 |
expectedFrontends := map[string]map[int64]*ProxyClientConnection{ |
| 669 |
"agent1": { |
| 670 |
int64(1): agent1ConnID1, |
| 671 |
int64(2): agent1ConnID2, |
| 672 |
}, |
| 673 |
"agent3": { |
| 674 |
int64(1): agent3ConnID1, |
| 675 |
}, |
| 676 |
} |
| 677 |
if e, a := expectedFrontends, p.established; !reflect.DeepEqual(e, a) { |
| 678 |
t.Errorf("expected %v, got %v", e, a) |
| 679 |
} |
| 680 |
} |
| 681 |
|
| 682 |
func TestRemoveEstablishedForStream(t *testing.T) { |
| 683 |
streamUID := "target-uuid" |
| 684 |
backend1 := &Backend{} |
| 685 |
backend2 := &Backend{} |
| 686 |
backend3 := &Backend{} |
| 687 |
agent1ConnID1 := &ProxyClientConnection{backend: backend1, frontend: &GrpcFrontend{streamUID: streamUID}} |
| 688 |
agent1ConnID2 := &ProxyClientConnection{backend: backend1} |
| 689 |
agent2ConnID1 := &ProxyClientConnection{backend: backend2, frontend: &GrpcFrontend{streamUID: streamUID}} |
| 690 |
agent2ConnID2 := &ProxyClientConnection{backend: backend2} |
| 691 |
agent3ConnID1 := &ProxyClientConnection{backend: backend3, frontend: &GrpcFrontend{streamUID: streamUID}} |
| 692 |
p := NewProxyServer("", []proxystrategies.ProxyStrategy{proxystrategies.ProxyStrategyDefault}, 1, nil, xfrChannelSize) |
| 693 |
p.addEstablished("agent1", int64(1), agent1ConnID1) |
| 694 |
p.addEstablished("agent1", int64(2), agent1ConnID2) |
| 695 |
p.addEstablished("agent2", int64(1), agent2ConnID1) |
| 696 |
p.addEstablished("agent2", int64(2), agent2ConnID2) |
| 697 |
p.addEstablished("agent3", int64(1), agent3ConnID1) |
| 698 |
p.removeEstablishedForStream(streamUID) |
| 699 |
expectedFrontends := map[string]map[int64]*ProxyClientConnection{ |
| 700 |
"agent1": { |
| 701 |
int64(2): agent1ConnID2, |
| 702 |
}, |
| 703 |
"agent2": { |
| 704 |
int64(2): agent2ConnID2, |
| 705 |
}, |
| 706 |
} |
| 707 |
if e, a := expectedFrontends, p.established; !reflect.DeepEqual(e, a) { |
| 708 |
t.Errorf("expected %v, got %v", e, a) |
| 709 |
} |
| 710 |
} |
| 711 |
|
| 712 |
func prepareFrontendConn(ctrl *gomock.Controller) *agentmock.MockAgentService_ConnectServer { |
| 713 |
// prepare the connection to fontend of proxy-server |
| 714 |
// TODO: replace with a mock ProxyService_ProxyServer |
| 715 |
frontendConn := agentmock.NewMockAgentService_ConnectServer(ctrl) |
| 716 |
frontendConnMD := metadata.MD{ |
| 717 |
":authority": []string{"127.0.0.1:8090"}, |
| 718 |
"content-type": []string{"application/grpc"}, |
| 719 |
"user-agent": []string{"grpc-go/1.42.0"}, |
| 720 |
} |
| 721 |
frontendConnCtx := metadata.NewIncomingContext(context.Background(), frontendConnMD) |
| 722 |
frontendConn.EXPECT().Context().Return(frontendConnCtx).AnyTimes() |
| 723 |
return frontendConn |
| 724 |
} |
| 725 |
|
| 726 |
func prepareAgentConnMD(t testing.TB, ctrl *gomock.Controller, proxyServer *ProxyServer, agentidentifiers []string) (*agentmock.MockAgentService_ConnectServer, *Backend) { |
| 727 |
t.Helper() |
| 728 |
if agentidentifiers == nil { |
| 729 |
agentidentifiers = []string{} |
| 730 |
} |
| 731 |
// prepare the the connection to agent of proxy-server |
| 732 |
agentConn := agentmock.NewMockAgentService_ConnectServer(ctrl) |
| 733 |
agentConnMD := metadata.MD{ |
| 734 |
":authority": []string{"127.0.0.1:8091"}, |
| 735 |
"agentid": []string{uuid.New().String()}, |
| 736 |
"agentidentifiers": agentidentifiers, |
| 737 |
"content-type": []string{"application/grpc"}, |
| 738 |
"user-agent": []string{"grpc-go/1.42.0"}, |
| 739 |
} |
| 740 |
agentConnCtx := metadata.NewIncomingContext(context.Background(), agentConnMD) |
| 741 |
agentConn.EXPECT().Context().Return(agentConnCtx).AnyTimes() |
| 742 |
backend, err := NewBackend(agentConn) |
| 743 |
if err != nil { |
| 744 |
t.Fatalf("Unexpected NewBackend error: %v", err) |
| 745 |
} |
| 746 |
proxyServer.addBackend(backend) |
| 747 |
return agentConn, backend |
| 748 |
} |
| 749 |
|
| 750 |
func baseServerProxyTestWithoutBackend(t *testing.T, validate func(*agentmock.MockAgentService_ConnectServer)) { |
| 751 |
ctrl := gomock.NewController(t) |
| 752 |
defer ctrl.Finish() |
| 753 |
|
| 754 |
frontendConn := prepareFrontendConn(ctrl) |
| 755 |
proxyServer := NewProxyServer(uuid.New().String(), []proxystrategies.ProxyStrategy{proxystrategies.ProxyStrategyDefault}, 1, &AgentTokenAuthenticationOptions{}, xfrChannelSize) |
| 756 |
|
| 757 |
validate(frontendConn) |
| 758 |
|
| 759 |
proxyServer.Proxy(frontendConn) |
| 760 |
} |
| 761 |
|
| 762 |
func baseServerProxyTestWithBackend(t *testing.T, validate func(*agentmock.MockAgentService_ConnectServer, *agentmock.MockAgentService_ConnectServer)) { |
| 763 |
ctrl := gomock.NewController(t) |
| 764 |
defer ctrl.Finish() |
| 765 |
|
| 766 |
frontendConn := prepareFrontendConn(ctrl) |
| 767 |
|
| 768 |
// prepare proxy server |
| 769 |
proxyServer := NewProxyServer(uuid.New().String(), []proxystrategies.ProxyStrategy{proxystrategies.ProxyStrategyDefault}, 1, &AgentTokenAuthenticationOptions{}, xfrChannelSize) |
| 770 |
|
| 771 |
agentConn, _ := prepareAgentConnMD(t, ctrl, proxyServer, nil) |
| 772 |
|
| 773 |
validate(frontendConn, agentConn) |
| 774 |
|
| 775 |
proxyServer.Proxy(frontendConn) |
| 776 |
} |
| 777 |
|
| 778 |
func TestServerProxyNoBackend(t *testing.T) { |
| 779 |
validate := func(frontendConn *agentmock.MockAgentService_ConnectServer) { |
| 780 |
// receive DIAL_REQ from frontend and proxy to backend |
| 781 |
dialReq := &client.Packet{ |
| 782 |
Type: client.PacketType_DIAL_REQ, |
| 783 |
Payload: &client.Packet_DialRequest{ |
| 784 |
DialRequest: &client.DialRequest{ |
| 785 |
Protocol: "tcp", |
| 786 |
Address: "127.0.0.1:8080", |
| 787 |
Random: 111, |
| 788 |
}, |
| 789 |
}, |
| 790 |
} |
| 791 |
|
| 792 |
dialResp := &client.Packet{ |
| 793 |
Type: client.PacketType_DIAL_RSP, |
| 794 |
Payload: &client.Packet_DialResponse{ |
| 795 |
DialResponse: &client.DialResponse{ |
| 796 |
Random: 111, |
| 797 |
Error: (&ErrNotFound{}).Error(), |
| 798 |
}}, |
| 799 |
} |
| 800 |
|
| 801 |
gomock.InOrder( |
| 802 |
frontendConn.EXPECT().Recv().Return(dialReq, nil).Times(1), |
| 803 |
frontendConn.EXPECT().Recv().Return(nil, io.EOF).Times(1), |
| 804 |
// NOTE(mainred): `Send` should come before `Recv` io.EOF, but we cannot add wait between |
| 805 |
// two Recvs, thus `Recv`` comes before `Send` |
| 806 |
frontendConn.EXPECT().Send(dialResp).Return(nil).Times(1), |
| 807 |
) |
| 808 |
|
| 809 |
} |
| 810 |
baseServerProxyTestWithoutBackend(t, validate) |
| 811 |
|
| 812 |
if err := metricstest.DefaultTester.ExpectServerDialFailure(metrics.DialFailureNoAgent, 1); err != nil { |
| 813 |
t.Error(err) |
| 814 |
} |
| 815 |
} |
| 816 |
|
| 817 |
func TestServerProxyNormalClose(t *testing.T) { |
| 818 |
validate := func(frontendConn, agentConn *agentmock.MockAgentService_ConnectServer) { |
| 819 |
const dialID = 111 |
| 820 |
const connectID = 123456 |
| 821 |
// receive DIAL_REQ from frontend and proxy to backend |
| 822 |
dialReq := dialReqPkt(dialID) |
| 823 |
data := dataPkt(connectID, []byte("hello world")) |
| 824 |
closeReq := closeReqPkt(connectID) |
| 825 |
|
| 826 |
gomock.InOrder( |
| 827 |
frontendConn.EXPECT().Recv().Return(dialReq, nil).Times(1), |
| 828 |
frontendConn.EXPECT().Recv().Return(data, nil).Times(1), |
| 829 |
frontendConn.EXPECT().Recv().Return(closeReq, nil).Times(1), |
| 830 |
frontendConn.EXPECT().Recv().Return(nil, io.EOF).Times(1), |
| 831 |
) |
| 832 |
gomock.InOrder( |
| 833 |
agentConn.EXPECT().Send(dialReq).Return(nil).Times(1), |
| 834 |
agentConn.EXPECT().Send(data).Return(nil).Times(1), |
| 835 |
agentConn.EXPECT().Send(closeReq).Return(nil).Times(1), |
| 836 |
agentConn.EXPECT().Send(dialClosePkt(dialID)).Return(nil).Times(1), |
| 837 |
) |
| 838 |
} |
| 839 |
baseServerProxyTestWithBackend(t, validate) |
| 840 |
} |
| 841 |
|
| 842 |
func TestServerProxyRecvChanFull(t *testing.T) { |
| 843 |
validate := func(frontendConn, agentConn *agentmock.MockAgentService_ConnectServer) { |
| 844 |
const dialID = 111 |
| 845 |
const connectID = 1 |
| 846 |
// receive DIAL_REQ from frontend and proxy to backend |
| 847 |
dialReq := dialReqPkt(dialID) |
| 848 |
data := dataPkt(connectID, []byte("hello world")) |
| 849 |
|
| 850 |
const defaultTimeout = 5 * time.Minute |
| 851 |
deadline := time.Now().Add(defaultTimeout) |
| 852 |
if testDeadline, ok := t.Deadline(); ok && testDeadline.Before(deadline) { |
| 853 |
deadline = testDeadline.Add(-1 * time.Second) |
| 854 |
} |
| 855 |
|
| 856 |
waitForMetricVal := func(expected float64) { |
| 857 |
err := wait.Poll(10*time.Millisecond, time.Until(deadline), func() (bool, error) { |
| 858 |
val := promtest.ToFloat64(metrics.Metrics.FullRecvChannel(metrics.Proxy)) |
| 859 |
return val == expected, nil |
| 860 |
}) |
| 861 |
if err != nil { |
| 862 |
t.Fatalf("Failed to observe expected metric: %v", err) |
| 863 |
} |
| 864 |
} |
| 865 |
|
| 866 |
expectMetricVal := func(expected float64) { |
| 867 |
val := promtest.ToFloat64(metrics.Metrics.FullRecvChannel(metrics.Proxy)) |
| 868 |
if val != expected { |
| 869 |
t.Errorf("Unexpected metric value: %v (expected %v)", val, expected) |
| 870 |
} |
| 871 |
} |
| 872 |
|
| 873 |
// WaitGroups for coordinating test stages. |
| 874 |
recvWG := sync.WaitGroup{} |
| 875 |
recvWG.Add(1) |
| 876 |
sendWG := sync.WaitGroup{} |
| 877 |
sendWG.Add(1) |
| 878 |
|
| 879 |
gomock.InOrder( |
| 880 |
frontendConn.EXPECT().Recv().Return(dialReq, nil), |
| 881 |
// First packet goes through to agentConn.Send |
| 882 |
frontendConn.EXPECT().Recv().Return(data, nil), |
| 883 |
// Next xfrChannelSize packets fill the channel. |
| 884 |
frontendConn.EXPECT().Recv().DoAndReturn(func() (*client.Packet, error) { |
| 885 |
// Wait for initial packet send before filling the channel. |
| 886 |
recvWG.Wait() |
| 887 |
return data, nil |
| 888 |
}), |
| 889 |
frontendConn.EXPECT().Recv().Return(data, nil).Times(xfrChannelSize-1), |
| 890 |
// Last packet should trigger channel full condition. |
| 891 |
frontendConn.EXPECT().Recv().DoAndReturn(func() (*client.Packet, error) { |
| 892 |
// Verify that the full channel condition hasn't triggered yet. |
| 893 |
expectMetricVal(0) |
| 894 |
return data, nil |
| 895 |
}), |
| 896 |
|
| 897 |
frontendConn.EXPECT().Recv().Return(closeReqPkt(1), nil), |
| 898 |
// Ensure that the go-routines don't deadlock if more packets are received before closing the connection. |
| 899 |
// This is a bit contrived, but exercises a possible failure scenario. |
| 900 |
frontendConn.EXPECT().Recv().Return(data, nil).Times(xfrChannelSize+1), |
| 901 |
frontendConn.EXPECT().Recv().Return(nil, io.EOF), |
| 902 |
) |
| 903 |
gomock.InOrder( |
| 904 |
agentConn.EXPECT().Send(dialReq).Return(nil), |
| 905 |
agentConn.EXPECT().Send(data).DoAndReturn(func(_ *client.Packet) error { |
| 906 |
// Channel should not be full at this point. |
| 907 |
expectMetricVal(0) |
| 908 |
recvWG.Done() // Proceed to fill the channel. |
| 909 |
|
| 910 |
// Block the send from completing until the full channel condition is detected. |
| 911 |
waitForMetricVal(1) |
| 912 |
return nil |
| 913 |
}), |
| 914 |
agentConn.EXPECT().Send(data).Return(nil).Times(xfrChannelSize+1), // Expect the remaining packets to be sent. |
| 915 |
agentConn.EXPECT().Send(closeReqPkt(1)).Return(nil), |
| 916 |
agentConn.EXPECT().Send(dialClosePkt(dialID)).Return(nil).Times(1), |
| 917 |
) |
| 918 |
} |
| 919 |
baseServerProxyTestWithBackend(t, validate) |
| 920 |
} |
| 921 |
|
| 922 |
func TestServerProxyNoDial(t *testing.T) { |
| 923 |
baseServerProxyTestWithBackend(t, func(frontendConn, _ *agentmock.MockAgentService_ConnectServer) { |
| 924 |
const connectID = 123456 |
| 925 |
data := &client.Packet{ |
| 926 |
Type: client.PacketType_DATA, |
| 927 |
Payload: &client.Packet_Data{ |
| 928 |
Data: &client.Data{ |
| 929 |
ConnectID: connectID, |
| 930 |
}, |
| 931 |
}, |
| 932 |
} |
| 933 |
|
| 934 |
gomock.InOrder( |
| 935 |
frontendConn.EXPECT().Recv().Return(data, nil), |
| 936 |
frontendConn.EXPECT().Recv().Return(nil, io.EOF), |
| 937 |
) |
| 938 |
frontendConn.EXPECT().Send(closeRspPkt(connectID, "backend not initialized")).Return(nil) |
| 939 |
}) |
| 940 |
} |
| 941 |
|
| 942 |
func TestServerProxyConnectionMismatch(t *testing.T) { |
| 943 |
baseServerProxyTestWithBackend(t, func(frontendConn, agentConn *agentmock.MockAgentService_ConnectServer) { |
| 944 |
const dialID = 111 |
| 945 |
const firstConnectID = 123456 |
| 946 |
const secondConnectID = 654321 |
| 947 |
dialReq := dialReqPkt(dialID) |
| 948 |
data := dataPkt(firstConnectID, []byte("hello")) |
| 949 |
mismatchedData := dataPkt(secondConnectID, []byte("world")) |
| 950 |
|
| 951 |
gomock.InOrder( |
| 952 |
frontendConn.EXPECT().Recv().Return(dialReq, nil), |
| 953 |
frontendConn.EXPECT().Recv().Return(data, nil), |
| 954 |
frontendConn.EXPECT().Recv().Return(mismatchedData, nil), |
| 955 |
frontendConn.EXPECT().Recv().Return(nil, io.EOF), |
| 956 |
) |
| 957 |
gomock.InOrder( |
| 958 |
agentConn.EXPECT().Send(dialReq).Return(nil), |
| 959 |
agentConn.EXPECT().Send(data).Return(nil), |
| 960 |
) |
| 961 |
agentConn.EXPECT().Send(closeReqPkt(secondConnectID)).Return(nil) |
| 962 |
agentConn.EXPECT().Send(closeReqPkt(firstConnectID)).Return(nil) |
| 963 |
frontendConn.EXPECT().Send(closeRspPkt(secondConnectID, "mismatched connection IDs")).Return(nil) |
| 964 |
frontendConn.EXPECT().Send(closeRspPkt(firstConnectID, "mismatched connection IDs")).Return(nil) |
| 965 |
agentConn.EXPECT().Send(dialClosePkt(dialID)).Return(nil).Times(1) |
| 966 |
}) |
| 967 |
} |
| 968 |
|
| 969 |
func TestReadyBackendsMetric(t *testing.T) { |
| 970 |
ctrl := gomock.NewController(t) |
| 971 |
defer ctrl.Finish() |
| 972 |
|
| 973 |
metrics.Metrics.Reset() |
| 974 |
|
| 975 |
p := NewProxyServer(uuid.New().String(), []proxystrategies.ProxyStrategy{proxystrategies.ProxyStrategyDefault}, 1, &AgentTokenAuthenticationOptions{}, xfrChannelSize) |
| 976 |
assertReadyBackendsMetric(t, 0) |
| 977 |
|
| 978 |
_, backend := prepareAgentConnMD(t, ctrl, p, nil) |
| 979 |
assertReadyBackendsMetric(t, 1) |
| 980 |
|
| 981 |
p.removeBackend(backend) |
| 982 |
assertReadyBackendsMetric(t, 0) |
| 983 |
} |
| 984 |
|
| 985 |
func TestTotalReadyBackendsMetric(t *testing.T) { |
| 986 |
ctrl := gomock.NewController(t) |
| 987 |
defer ctrl.Finish() |
| 988 |
|
| 989 |
metrics.Metrics.Reset() |
| 990 |
|
| 991 |
p := NewProxyServer(uuid.New().String(), []proxystrategies.ProxyStrategy{proxystrategies.ProxyStrategyDefault, proxystrategies.ProxyStrategyDestHost}, 1, &AgentTokenAuthenticationOptions{}, xfrChannelSize) |
| 992 |
assertTotalReadyBackendsMetric(t, map[string]int{proxystrategies.ProxyStrategyDefault.String(): 0, proxystrategies.ProxyStrategyDestHost.String(): 0}) |
| 993 |
|
| 994 |
_, backend1 := prepareAgentConnMD(t, ctrl, p, nil) |
| 995 |
assertTotalReadyBackendsMetric(t, map[string]int{proxystrategies.ProxyStrategyDefault.String(): 1, proxystrategies.ProxyStrategyDestHost.String(): 0}) |
| 996 |
|
| 997 |
// Add a backend with IPv4 agent identifier. |
| 998 |
_, backend2 := prepareAgentConnMD(t, ctrl, p, []string{"host=localhost"}) |
| 999 |
assertTotalReadyBackendsMetric(t, map[string]int{proxystrategies.ProxyStrategyDefault.String(): 2, proxystrategies.ProxyStrategyDestHost.String(): 1}) |
| 1000 |
|
| 1001 |
p.removeBackend(backend1) |
| 1002 |
p.removeBackend(backend2) |
| 1003 |
assertTotalReadyBackendsMetric(t, map[string]int{proxystrategies.ProxyStrategyDefault.String(): 0, proxystrategies.ProxyStrategyDestHost.String(): 0}) |
| 1004 |
} |
| 1005 |
|
| 1006 |
func dialReqPkt(dialID int64) *client.Packet { |
| 1007 |
return &client.Packet{ |
| 1008 |
Type: client.PacketType_DIAL_REQ, |
| 1009 |
Payload: &client.Packet_DialRequest{ |
| 1010 |
DialRequest: &client.DialRequest{ |
| 1011 |
Protocol: "tcp", |
| 1012 |
Address: "127.0.0.1:8080", |
| 1013 |
Random: dialID, |
| 1014 |
}, |
| 1015 |
}, |
| 1016 |
} |
| 1017 |
} |
| 1018 |
|
| 1019 |
func dataPkt(connectID int64, data []byte) *client.Packet { |
| 1020 |
return &client.Packet{ |
| 1021 |
Type: client.PacketType_DATA, |
| 1022 |
Payload: &client.Packet_Data{ |
| 1023 |
Data: &client.Data{ |
| 1024 |
ConnectID: connectID, |
| 1025 |
Data: data, |
| 1026 |
}, |
| 1027 |
}, |
| 1028 |
} |
| 1029 |
} |
| 1030 |
|
| 1031 |
func closeReqPkt(connectID int64) *client.Packet { |
| 1032 |
return &client.Packet{ |
| 1033 |
Type: client.PacketType_CLOSE_REQ, |
| 1034 |
Payload: &client.Packet_CloseRequest{ |
| 1035 |
CloseRequest: &client.CloseRequest{ |
| 1036 |
ConnectID: connectID, |
| 1037 |
}}, |
| 1038 |
} |
| 1039 |
} |
| 1040 |
|
| 1041 |
func closeRspPkt(connectID int64, errMsg string) *client.Packet { |
| 1042 |
return &client.Packet{ |
| 1043 |
Type: client.PacketType_CLOSE_RSP, |
| 1044 |
Payload: &client.Packet_CloseResponse{ |
| 1045 |
CloseResponse: &client.CloseResponse{ |
| 1046 |
ConnectID: connectID, |
| 1047 |
Error: errMsg, |
| 1048 |
}, |
| 1049 |
}, |
| 1050 |
} |
| 1051 |
} |
| 1052 |
|
| 1053 |
func assertEstablishedConnsMetric(t testing.TB, expect int) { |
| 1054 |
t.Helper() |
| 1055 |
if err := metricstest.DefaultTester.ExpectServerEstablishedConns(expect); err != nil { |
| 1056 |
t.Errorf("Expected %d %s metric: %v", expect, "established_connections", err) |
| 1057 |
} |
| 1058 |
} |
| 1059 |
|
| 1060 |
func pendingDialCount(p *ProxyServer) int { |
| 1061 |
p.PendingDial.mu.RLock() |
| 1062 |
defer p.PendingDial.mu.RUnlock() |
| 1063 |
return len(p.PendingDial.pendingDial) |
| 1064 |
} |
| 1065 |
|
| 1066 |
func assertReadyBackendsMetric(t testing.TB, expect int) { |
| 1067 |
t.Helper() |
| 1068 |
if err := metricstest.DefaultTester.ExpectServerReadyBackends(expect); err != nil { |
| 1069 |
t.Errorf("Expected %d %s metric: %v", expect, "ready_backend_connections", err) |
| 1070 |
} |
| 1071 |
} |
| 1072 |
|
| 1073 |
func assertTotalReadyBackendsMetric(t testing.TB, expect map[string]int) { |
| 1074 |
t.Helper() |
| 1075 |
if err := metricstest.DefaultTester.ExpectServerTotalReadyBackends(expect); err != nil { |
| 1076 |
t.Errorf("Expected %s metric for each proxy strategy %+v, but got error: %v", "ready_backends", expect, err) |
| 1077 |
} |
| 1078 |
} |
| 1079 |
|
| 1080 |
func dialClosePkt(dialID int64) *client.Packet { |
| 1081 |
return &client.Packet{ |
| 1082 |
Type: client.PacketType_DIAL_CLS, |
| 1083 |
Payload: &client.Packet_CloseDial{ |
| 1084 |
CloseDial: &client.CloseDial{ |
| 1085 |
Random: dialID, |
| 1086 |
}, |
| 1087 |
}, |
| 1088 |
} |
| 1089 |
} |