| 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 | "bytes" |
| 21 | "context" |
| 22 | "errors" |
| 23 | "fmt" |
| 24 | "io" |
| 25 | "net/http" |
| 26 | runpprof "runtime/pprof" |
| 27 | "strconv" |
| 28 | "strings" |
| 29 | "sync" |
| 30 | "time" |
| 31 | |
| 32 | "github.com/google/uuid" |
| 33 | "google.golang.org/grpc/codes" |
| 34 | "google.golang.org/grpc/metadata" |
| 35 | "google.golang.org/grpc/status" |
| 36 | authv1 "k8s.io/api/authentication/v1" |
| 37 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 38 | "k8s.io/client-go/kubernetes" |
| 39 | "k8s.io/klog/v2" |
| 40 | |
| 41 | commonmetrics "sigs.k8s.io/apiserver-network-proxy/konnectivity-client/pkg/common/metrics" |
| 42 | "sigs.k8s.io/apiserver-network-proxy/konnectivity-client/proto/client" |
| 43 | "sigs.k8s.io/apiserver-network-proxy/pkg/server/metrics" |
| 44 | "sigs.k8s.io/apiserver-network-proxy/pkg/util" |
| 45 | "sigs.k8s.io/apiserver-network-proxy/proto/agent" |
| 46 | "sigs.k8s.io/apiserver-network-proxy/proto/header" |
| 47 | ) |
| 48 | |
| 49 | type key int |
| 50 | |
| 51 | type GrpcFrontend struct { |
| 52 | stream client.ProxyService_ProxyServer |
| 53 | streamUID string |
| 54 | sendLock sync.Mutex |
| 55 | recvLock sync.Mutex |
| 56 | } |
| 57 | |
| 58 | func (g *GrpcFrontend) Send(pkt *client.Packet) error { |
| 59 | g.sendLock.Lock() |
| 60 | defer g.sendLock.Unlock() |
| 61 | |
| 62 | const segment = commonmetrics.SegmentToClient |
| 63 | metrics.Metrics.ObservePacket(segment, pkt.Type) |
| 64 | err := g.stream.Send(pkt) |
| 65 | if err != nil { |
| 66 | metrics.Metrics.ObserveStreamError(segment, err, pkt.Type) |
| 67 | } |
| 68 | return err |
| 69 | } |
| 70 | |
| 71 | func (g *GrpcFrontend) Recv() (*client.Packet, error) { |
| 72 | g.recvLock.Lock() |
| 73 | defer g.recvLock.Unlock() |
| 74 | |
| 75 | const segment = commonmetrics.SegmentFromClient |
| 76 | pkt, err := g.stream.Recv() |
| 77 | if err != nil { |
| 78 | if err != io.EOF { |
| 79 | metrics.Metrics.ObserveStreamErrorNoPacket(segment, err) |
| 80 | } |
| 81 | return nil, err |
| 82 | } |
| 83 | metrics.Metrics.ObservePacket(segment, pkt.Type) |
| 84 | return pkt, nil |
| 85 | } |
| 86 | |
| 87 | const ( |
| 88 | ModeGRPC = "grpc" |
| 89 | ModeHTTPConnect = "http-connect" |
| 90 | ) |
| 91 | |
| 92 | type ProxyClientConnection struct { |
| 93 | Mode string |
| 94 | HTTP io.ReadWriter |
| 95 | frontend *GrpcFrontend |
| 96 | CloseHTTP func() error |
| 97 | connected chan struct{} |
| 98 | dialID int64 |
| 99 | connectID int64 |
| 100 | agentID string |
| 101 | start time.Time |
| 102 | backend *Backend |
| 103 | dialAddress string // cached for logging |
| 104 | } |
| 105 | |
| 106 | const ( |
| 107 | destHostKey key = iota |
| 108 | ) |
| 109 | |
| 110 | func (c *ProxyClientConnection) send(pkt *client.Packet) error { |
| 111 | defer func(start time.Time) { metrics.Metrics.ObserveFrontendWriteLatency(time.Since(start)) }(time.Now()) |
| 112 | if c.Mode == ModeGRPC { |
| 113 | return c.frontend.Send(pkt) |
| 114 | } |
| 115 | if c.Mode == ModeHTTPConnect { |
| 116 | if pkt.Type == client.PacketType_CLOSE_RSP { |
| 117 | return c.CloseHTTP() |
| 118 | } else if pkt.Type == client.PacketType_DIAL_CLS { |
| 119 | return c.CloseHTTP() |
| 120 | } else if pkt.Type == client.PacketType_DATA { |
| 121 | _, err := c.HTTP.Write(pkt.GetData().Data) |
| 122 | return err |
| 123 | } else if pkt.Type == client.PacketType_DIAL_RSP { |
| 124 | if pkt.GetDialResponse().Error != "" { |
| 125 | body := bytes.NewBufferString(pkt.GetDialResponse().Error) |
| 126 | t := http.Response{ |
| 127 | StatusCode: 503, |
| 128 | Body: io.NopCloser(body), |
| 129 | } |
| 130 | |
| 131 | t.Write(c.HTTP) |
| 132 | return c.CloseHTTP() |
| 133 | } |
| 134 | return nil |
| 135 | } |
| 136 | return fmt.Errorf("attempt to send via unrecognized connection type %v", pkt.Type) |
| 137 | } |
| 138 | return fmt.Errorf("attempt to send via unrecognized connection mode %q", c.Mode) |
| 139 | } |
| 140 | |
| 141 | func NewPendingDialManager() *PendingDialManager { |
| 142 | return &PendingDialManager{ |
| 143 | pendingDial: make(map[int64]*ProxyClientConnection), |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | type PendingDialManager struct { |
| 148 | mu sync.RWMutex |
| 149 | pendingDial map[int64]*ProxyClientConnection |
| 150 | } |
| 151 | |
| 152 | func (pm *PendingDialManager) Add(random int64, clientConn *ProxyClientConnection) { |
| 153 | pm.mu.Lock() |
| 154 | defer pm.mu.Unlock() |
| 155 | pm.pendingDial[random] = clientConn |
| 156 | metrics.Metrics.SetPendingDialCount(len(pm.pendingDial)) |
| 157 | } |
| 158 | |
| 159 | func (pm *PendingDialManager) Remove(random int64) *ProxyClientConnection { |
| 160 | pm.mu.Lock() |
| 161 | defer pm.mu.Unlock() |
| 162 | pd := pm.pendingDial[random] |
| 163 | delete(pm.pendingDial, random) |
| 164 | metrics.Metrics.SetPendingDialCount(len(pm.pendingDial)) |
| 165 | return pd |
| 166 | } |
| 167 | |
| 168 | // removeForStream removes and returns all pending ProxyClientConnection associated with a |
| 169 | // given Proxy gRPC connection (expected to be at most 1 while konnectivity-client API gives |
| 170 | // single-use tunnels). |
| 171 | func (pm *PendingDialManager) removeForStream(streamUID string) []*ProxyClientConnection { |
| 172 | var ret []*ProxyClientConnection |
| 173 | if streamUID == "" { |
| 174 | return ret |
| 175 | } |
| 176 | pm.mu.Lock() |
| 177 | defer pm.mu.Unlock() |
| 178 | for dialID, frontend := range pm.pendingDial { |
| 179 | if frontend.frontend == nil { |
| 180 | continue |
| 181 | } |
| 182 | if frontend.frontend.streamUID == streamUID { |
| 183 | delete(pm.pendingDial, dialID) |
| 184 | ret = append(ret, frontend) |
| 185 | } |
| 186 | } |
| 187 | return ret |
| 188 | } |
| 189 | |
| 190 | // ProxyServer |
| 191 | type ProxyServer struct { |
| 192 | // BackendManagers contains a list of BackendManagers |
| 193 | BackendManagers []BackendManager |
| 194 | |
| 195 | // Readiness reports if the proxy server is ready, i.e., if the proxy |
| 196 | // server has connections to proxy agents (backends). Note that the |
| 197 | // proxy server does not check the healthiness of the connections, |
| 198 | // though the proxy agents do, so this readiness check might report |
| 199 | // ready but there is no healthy connection. |
| 200 | Readiness ReadinessManager |
| 201 | |
| 202 | // fmu protects established. |
| 203 | fmu sync.RWMutex |
| 204 | // conn = Frontend[agentID][connID] |
| 205 | established map[string]map[int64]*ProxyClientConnection |
| 206 | |
| 207 | PendingDial *PendingDialManager |
| 208 | |
| 209 | serverID string // unique ID of this server |
| 210 | serverCount int // Number of proxy server instances, should be 1 unless it is a HA server. |
| 211 | |
| 212 | // agent authentication |
| 213 | AgentAuthenticationOptions *AgentTokenAuthenticationOptions |
| 214 | |
| 215 | // TODO: move strategies into BackendStorage |
| 216 | proxyStrategies []ProxyStrategy |
| 217 | xfrChannelSize int |
| 218 | } |
| 219 | |
| 220 | // AgentTokenAuthenticationOptions contains list of parameters required for agent token based authentication |
| 221 | type AgentTokenAuthenticationOptions struct { |
| 222 | Enabled bool |
| 223 | AgentNamespace string |
| 224 | AgentServiceAccount string |
| 225 | AuthenticationAudience string |
| 226 | KubernetesClient kubernetes.Interface |
| 227 | } |
| 228 | |
| 229 | var _ agent.AgentServiceServer = &ProxyServer{} |
| 230 | |
| 231 | var _ client.ProxyServiceServer = &ProxyServer{} |
| 232 | |
| 233 | func genContext(proxyStrategies []ProxyStrategy, reqHost string) context.Context { |
| 234 | ctx := context.Background() |
| 235 | for _, ps := range proxyStrategies { |
| 236 | switch ps { |
| 237 | case ProxyStrategyDestHost: |
| 238 | addr := util.RemovePortFromHost(reqHost) |
| 239 | ctx = context.WithValue(ctx, destHostKey, addr) |
| 240 | } |
| 241 | } |
| 242 | return ctx |
| 243 | } |
| 244 | |
| 245 | func (s *ProxyServer) getBackend(reqHost string) (*Backend, error) { |
| 246 | ctx := genContext(s.proxyStrategies, reqHost) |
| 247 | for _, bm := range s.BackendManagers { |
| 248 | be, err := bm.Backend(ctx) |
| 249 | if err == nil { |
| 250 | return be, nil |
| 251 | } |
| 252 | if ignoreNotFound(err) != nil { |
| 253 | // if can't find a backend through current BackendManager, move on |
| 254 | // to the next one |
| 255 | return nil, err |
| 256 | } |
| 257 | } |
| 258 | return nil, &ErrNotFound{} |
| 259 | } |
| 260 | |
| 261 | func (s *ProxyServer) addBackend(backend *Backend) { |
| 262 | // TODO: refactor BackendStorage to acquire lock once, not up to 3 times. |
| 263 | for _, bm := range s.BackendManagers { |
| 264 | bm.AddBackend(backend) |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | func (s *ProxyServer) removeBackend(backend *Backend) { |
| 269 | for _, bm := range s.BackendManagers { |
| 270 | bm.RemoveBackend(backend) |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | func (s *ProxyServer) addEstablished(agentID string, connID int64, p *ProxyClientConnection) { |
| 275 | s.fmu.Lock() |
| 276 | defer s.fmu.Unlock() |
| 277 | if _, ok := s.established[agentID]; !ok { |
| 278 | s.established[agentID] = make(map[int64]*ProxyClientConnection) |
| 279 | } |
| 280 | s.established[agentID][connID] = p |
| 281 | |
| 282 | metrics.Metrics.SetEstablishedConnCount(s.getCount(s.established)) |
| 283 | } |
| 284 | |
| 285 | func (s *ProxyServer) removeEstablished(agentID string, connID int64) *ProxyClientConnection { |
| 286 | var ret *ProxyClientConnection |
| 287 | s.fmu.Lock() |
| 288 | defer s.fmu.Unlock() |
| 289 | conns, ok := s.established[agentID] |
| 290 | if !ok { |
| 291 | return nil |
| 292 | } |
| 293 | if ret, ok = conns[connID]; !ok { |
| 294 | return nil |
| 295 | } |
| 296 | delete(s.established[agentID], connID) |
| 297 | if len(s.established[agentID]) == 0 { |
| 298 | delete(s.established, agentID) |
| 299 | } |
| 300 | metrics.Metrics.SetEstablishedConnCount(s.getCount(s.established)) |
| 301 | return ret |
| 302 | } |
| 303 | |
| 304 | func (s *ProxyServer) getFrontend(agentID string, connID int64) (*ProxyClientConnection, error) { |
| 305 | s.fmu.RLock() |
| 306 | defer s.fmu.RUnlock() |
| 307 | conns, ok := s.established[agentID] |
| 308 | if !ok { |
| 309 | return nil, fmt.Errorf("can't find agentID %s in the established", agentID) |
| 310 | } |
| 311 | conn, ok := conns[connID] |
| 312 | if !ok { |
| 313 | return nil, fmt.Errorf("can't find connID %d in the established[%s]", connID, agentID) |
| 314 | } |
| 315 | return conn, nil |
| 316 | } |
| 317 | |
| 318 | func (s *ProxyServer) removeEstablishedForBackendConn(agentID string, backend *Backend) ([]*ProxyClientConnection, error) { |
| 319 | var ret []*ProxyClientConnection |
| 320 | if backend == nil { |
| 321 | return ret, nil |
| 322 | } |
| 323 | s.fmu.Lock() |
| 324 | defer s.fmu.Unlock() |
| 325 | established, ok := s.established[agentID] |
| 326 | if !ok { |
| 327 | return nil, fmt.Errorf("can't find agentID %s in the established", agentID) |
| 328 | } |
| 329 | for _, frontend := range established { |
| 330 | if frontend.backend == backend { |
| 331 | delete(s.established, agentID) |
| 332 | ret = append(ret, frontend) |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | metrics.Metrics.SetEstablishedConnCount(s.getCount(s.established)) |
| 337 | return ret, nil |
| 338 | } |
| 339 | |
| 340 | func (s *ProxyServer) getCount(established map[string](map[int64]*ProxyClientConnection)) int { |
| 341 | count := 0 |
| 342 | for _, frontend := range established { |
| 343 | count = count + len(frontend) |
| 344 | } |
| 345 | return count |
| 346 | } |
| 347 | |
| 348 | // removeEstablishedForStream removes and returns all established ProxyClientConnection associated with a given |
| 349 | // Proxy gRPC connection (expected to be at most 1 while konnectivity-client API gives single-use |
| 350 | // tunnels). |
| 351 | func (s *ProxyServer) removeEstablishedForStream(streamUID string) []*ProxyClientConnection { |
| 352 | var ret []*ProxyClientConnection |
| 353 | if streamUID == "" { |
| 354 | return ret |
| 355 | } |
| 356 | s.fmu.Lock() |
| 357 | defer s.fmu.Unlock() |
| 358 | for agentID, established := range s.established { |
| 359 | for connID, frontend := range established { |
| 360 | if frontend.frontend == nil { |
| 361 | continue |
| 362 | } |
| 363 | if frontend.frontend.streamUID == streamUID { |
| 364 | delete(established, connID) |
| 365 | ret = append(ret, frontend) |
| 366 | } |
| 367 | } |
| 368 | if len(established) == 0 { |
| 369 | delete(s.established, agentID) |
| 370 | } |
| 371 | } |
| 372 | return ret |
| 373 | } |
| 374 | |
| 375 | // NewProxyServer creates a new ProxyServer instance |
| 376 | func NewProxyServer(serverID string, proxyStrategies []ProxyStrategy, serverCount int, agentAuthenticationOptions *AgentTokenAuthenticationOptions, channelSize int) *ProxyServer { |
| 377 | var bms []BackendManager |
| 378 | for _, ps := range proxyStrategies { |
| 379 | switch ps { |
| 380 | case ProxyStrategyDestHost: |
| 381 | bms = append(bms, NewDestHostBackendManager()) |
| 382 | case ProxyStrategyDefault: |
| 383 | bms = append(bms, NewDefaultBackendManager()) |
| 384 | case ProxyStrategyDefaultRoute: |
| 385 | bms = append(bms, NewDefaultRouteBackendManager()) |
| 386 | default: |
| 387 | klog.ErrorS(nil, "Unknown proxy strategy", "strategy", ps) |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | return &ProxyServer{ |
| 392 | established: make(map[string](map[int64]*ProxyClientConnection)), |
| 393 | PendingDial: NewPendingDialManager(), |
| 394 | serverID: serverID, |
| 395 | serverCount: serverCount, |
| 396 | BackendManagers: bms, |
| 397 | AgentAuthenticationOptions: agentAuthenticationOptions, |
| 398 | // use the first backend-manager as the Readiness Manager |
| 399 | Readiness: bms[0], |
| 400 | proxyStrategies: proxyStrategies, |
| 401 | xfrChannelSize: channelSize, |
| 402 | } |
| 403 | } |
| 404 | |
| 405 | // Proxy handles incoming streams from gRPC frontend. |
| 406 | func (s *ProxyServer) Proxy(stream client.ProxyService_ProxyServer) error { |
| 407 | metrics.Metrics.ConnectionInc(metrics.Proxy) |
| 408 | defer metrics.Metrics.ConnectionDec(metrics.Proxy) |
| 409 | |
| 410 | md, ok := metadata.FromIncomingContext(stream.Context()) |
| 411 | if !ok { |
| 412 | return fmt.Errorf("failed to get context") |
| 413 | } |
| 414 | userAgent := md.Get(header.UserAgent) |
| 415 | streamUID := uuid.New().String() |
| 416 | klog.V(5).InfoS("Proxy request from client", "userAgent", userAgent, "serverID", s.serverID, "streamUID", streamUID) |
| 417 | |
| 418 | recvCh := make(chan *client.Packet, s.xfrChannelSize) |
| 419 | stopCh := make(chan error, 1) |
| 420 | |
| 421 | frontend := GrpcFrontend{ |
| 422 | stream: stream, |
| 423 | streamUID: streamUID, |
| 424 | } |
| 425 | |
| 426 | defer func() { |
| 427 | // The frontend stream and goroutines are completely shut down, so we will never get a |
| 428 | // subsequent close message from the frontend. This can happen for several reasons, such as |
| 429 | // stream canceled. Clean any lingering tunnel connections to avoid resource leaks. |
| 430 | for _, p := range s.PendingDial.removeForStream(streamUID) { |
| 431 | klog.V(2).InfoS("frontend stream shutdown, cleaning dial", "dialID", p.dialID) |
| 432 | // TODO: add agent support to handle this |
| 433 | s.sendBackendDialClose(p.backend, p.dialID, "frontend stream shutdown") |
| 434 | } |
| 435 | for _, f := range s.removeEstablishedForStream(streamUID) { |
| 436 | klog.V(2).InfoS("frontend stream shutdown, cleaning frontend", "connectionID", f.connectID, "dialID", f.dialID) |
| 437 | s.sendBackendClose(f.backend, f.connectID, f.dialID, "frontend stream shutdown") |
| 438 | } |
| 439 | }() |
| 440 | |
| 441 | labels := runpprof.Labels( |
| 442 | "serverCount", strconv.Itoa(s.serverCount), |
| 443 | "userAgent", strings.Join(userAgent, ", "), |
| 444 | ) |
| 445 | // Start goroutine to receive packets from frontend and push to recvCh |
| 446 | go runpprof.Do(context.Background(), labels, func(context.Context) { s.readFrontendToChannel(&frontend, userAgent, recvCh, stopCh) }) |
| 447 | |
| 448 | s.serveRecvFrontend(&frontend, recvCh) |
| 449 | |
| 450 | return <-stopCh |
| 451 | } |
| 452 | |
| 453 | func (s *ProxyServer) readFrontendToChannel(frontend *GrpcFrontend, userAgent []string, recvCh chan *client.Packet, stopCh chan error) { |
| 454 | defer close(stopCh) |
| 455 | defer close(recvCh) |
| 456 | |
| 457 | for { |
| 458 | in, err := frontend.Recv() |
| 459 | if err == io.EOF { |
| 460 | klog.V(2).InfoS("Receive stream from frontend closed", "userAgent", userAgent) |
| 461 | return |
| 462 | } |
| 463 | if err != nil { |
| 464 | if status.Code(err) == codes.Canceled { |
| 465 | klog.V(2).InfoS("Stream read from frontend cancelled", "userAgent", userAgent) |
| 466 | } else { |
| 467 | klog.ErrorS(err, "Stream read from frontend failure", "userAgent", userAgent) |
| 468 | } |
| 469 | stopCh <- err |
| 470 | return |
| 471 | } |
| 472 | |
| 473 | select { |
| 474 | case recvCh <- in: // Send didn't block, carry on. |
| 475 | default: // Send blocked; record it and try again. |
| 476 | klog.V(2).InfoS("Receive channel from frontend is full", "userAgent", userAgent) |
| 477 | fullRecvChannelMetric := metrics.Metrics.FullRecvChannel(metrics.Proxy) |
| 478 | fullRecvChannelMetric.Inc() |
| 479 | recvCh <- in |
| 480 | fullRecvChannelMetric.Dec() |
| 481 | } |
| 482 | } |
| 483 | } |
| 484 | |
| 485 | func (s *ProxyServer) serveRecvFrontend(frontend *GrpcFrontend, recvCh <-chan *client.Packet) { |
| 486 | klog.V(5).Infoln("start serving frontend stream") |
| 487 | |
| 488 | var firstConnID int64 |
| 489 | // The first packet should be a DIAL_REQ, we will randomly get a |
| 490 | // backend from the BackendManger then. |
| 491 | // TODO: either add agentID to protocol (DATA, CLOSE_RSP, etc) or replace {agentID, |
| 492 | // connectionID} with a simpler key (#462). |
| 493 | var backend *Backend |
| 494 | var err error |
| 495 | |
| 496 | defer func() { |
| 497 | klog.V(5).InfoS("Close frontend streaming", "connectionID", firstConnID, "streamUID", frontend.streamUID) |
| 498 | if backend == nil { |
| 499 | klog.V(2).InfoS("Streaming closed before backend intialized") |
| 500 | } |
| 501 | |
| 502 | // As the read side of the recvCh channel, we cannot close it. |
| 503 | // However readFrontendToChannel() may be blocked writing to the channel, |
| 504 | // so we need to consume the channel until it is closed. |
| 505 | discardedPktCount := 0 |
| 506 | for range recvCh { |
| 507 | // Ignore values as this indicates there was a problem |
| 508 | // with the remote connection. |
| 509 | discardedPktCount++ |
| 510 | } |
| 511 | if discardedPktCount > 0 { |
| 512 | klog.V(2).InfoS("Discard packets while exiting serveRecvFrontend", "pktCount", discardedPktCount, "connectionID", firstConnID) |
| 513 | } |
| 514 | }() |
| 515 | |
| 516 | for pkt := range recvCh { |
| 517 | switch pkt.Type { |
| 518 | case client.PacketType_DIAL_REQ: |
| 519 | random := pkt.GetDialRequest().Random |
| 520 | address := pkt.GetDialRequest().Address |
| 521 | klog.V(3).InfoS("Received DIAL_REQ", "dialID", random, "dialAddress", address) |
| 522 | // TODO: if we track what agent has historically served |
| 523 | // the address, then we can send the Dial_REQ to the |
| 524 | // same agent. That way we save the agent from creating |
| 525 | // a new connection to the address. |
| 526 | backend, err = s.getBackend(address) |
| 527 | if err != nil { |
| 528 | klog.ErrorS(err, "Failed to get a backend", "dialID", random) |
| 529 | metrics.Metrics.ObserveDialFailure(metrics.DialFailureNoAgent) |
| 530 | |
| 531 | resp := &client.Packet{ |
| 532 | Type: client.PacketType_DIAL_RSP, |
| 533 | Payload: &client.Packet_DialResponse{ |
| 534 | DialResponse: &client.DialResponse{ |
| 535 | Random: random, |
| 536 | Error: err.Error(), |
| 537 | }, |
| 538 | }, |
| 539 | } |
| 540 | if err := frontend.Send(resp); err != nil { |
| 541 | klog.V(5).InfoS("Failed to send DIAL_RSP for no backend", "error", err, "dialID", random) |
| 542 | } |
| 543 | // The Dial is failing; no reason to keep this goroutine. |
| 544 | return |
| 545 | } |
| 546 | s.PendingDial.Add( |
| 547 | random, |
| 548 | &ProxyClientConnection{ |
| 549 | Mode: "grpc", |
| 550 | frontend: frontend, |
| 551 | dialID: random, |
| 552 | connected: make(chan struct{}), |
| 553 | start: time.Now(), |
| 554 | backend: backend, |
| 555 | dialAddress: address, |
| 556 | }) |
| 557 | if err := backend.Send(pkt); err != nil { |
| 558 | klog.ErrorS(err, "DIAL_REQ to Backend failed", "dialID", random) |
| 559 | } else { |
| 560 | klog.V(5).InfoS("DIAL_REQ sent to backend", "dialID", random) |
| 561 | } |
| 562 | |
| 563 | case client.PacketType_CLOSE_REQ: |
| 564 | connID := pkt.GetCloseRequest().ConnectID |
| 565 | klog.V(5).InfoS("Received CLOSE_REQ", "connectionID", connID) |
| 566 | if backend == nil { |
| 567 | klog.V(2).InfoS("Backend has not been initialized for this connection", "connectionID", connID) |
| 568 | s.sendFrontendClose(frontend, connID, "backend uninitialized") |
| 569 | continue |
| 570 | } |
| 571 | if err := backend.Send(pkt); err != nil { |
| 572 | // TODO: retry with other backends connecting to this agent. |
| 573 | klog.ErrorS(err, "CLOSE_REQ to Backend failed", "connectionID", connID) |
| 574 | s.sendFrontendClose(frontend, connID, "CLOSE_REQ to backend failed") |
| 575 | } else { |
| 576 | klog.V(5).InfoS("CLOSE_REQ sent to backend", "connectionID", connID) |
| 577 | } |
| 578 | klog.V(3).InfoS("Closing frontend streaming per CLOSE_REQ", "connectionID", connID) |
| 579 | return |
| 580 | |
| 581 | case client.PacketType_DIAL_CLS: |
| 582 | random := pkt.GetCloseDial().Random |
| 583 | klog.V(5).InfoS("Received DIAL_CLOSE", "dialID", random) |
| 584 | // Currently not worrying about backend as we do not have an established connection, |
| 585 | if pd := s.PendingDial.Remove(random); pd != nil { |
| 586 | klog.ErrorS(nil, "Dial cancelled (DIAL_CLS) by frontend", |
| 587 | "dialID", random, |
| 588 | "dialAddress", pd.dialAddress, |
| 589 | "dialDuration", time.Since(pd.start), |
| 590 | ) |
| 591 | metrics.Metrics.ObserveDialFailure(metrics.DialFailureFrontendClose) |
| 592 | } else { |
| 593 | // TODO: Fix the leaked connection due to race (client cancels a pending dial but |
| 594 | // server has completed the dial). |
| 595 | klog.ErrorS(nil, "Unrecognized dial cancelled (DIAL_CLS) by frontend", "dialID", random) |
| 596 | } |
| 597 | |
| 598 | case client.PacketType_DATA: |
| 599 | connID := pkt.GetData().ConnectID |
| 600 | data := pkt.GetData().Data |
| 601 | klog.V(5).InfoS("Received data from connection", "bytes", len(data), "connectionID", connID) |
| 602 | if backend == nil { |
| 603 | klog.V(2).InfoS("Backend has not been initialized for this connection", "connectionID", connID) |
| 604 | s.sendFrontendClose(frontend, connID, "backend not initialized") |
| 605 | return |
| 606 | } |
| 607 | |
| 608 | if connID == 0 { |
| 609 | klog.ErrorS(nil, "Received packet missing ConnectID from frontend", "packetType", "DATA") |
| 610 | continue |
| 611 | } |
| 612 | if firstConnID == 0 { |
| 613 | firstConnID = connID |
| 614 | } else if firstConnID != connID { |
| 615 | klog.ErrorS(nil, "Data does not match first connection id", "firstConnectionID", firstConnID, "connectionID", connID) |
| 616 | // Something went very wrong if we get here. Close both connections to avoid leaks. |
| 617 | s.sendBackendClose(backend, connID, 0, "mismatched connection IDs") |
| 618 | s.sendBackendClose(backend, firstConnID, 0, "mismatched connection IDs") |
| 619 | s.sendFrontendClose(frontend, connID, "mismatched connection IDs") |
| 620 | s.sendFrontendClose(frontend, firstConnID, "mismatched connection IDs") |
| 621 | return |
| 622 | } |
| 623 | if err := backend.Send(pkt); err != nil { |
| 624 | // TODO: retry with other backends connecting to this agent. |
| 625 | klog.ErrorS(err, "DATA to Backend failed", "connectionID", connID) |
| 626 | continue |
| 627 | } |
| 628 | klog.V(5).Infoln("DATA sent to Backend") |
| 629 | |
| 630 | default: |
| 631 | klog.V(5).InfoS("Ignoring unrecognized packet from frontend", |
| 632 | "type", pkt.Type, "connectionID", firstConnID) |
| 633 | } |
| 634 | } |
| 635 | } |
| 636 | |
| 637 | func (s *ProxyServer) validateAuthToken(ctx context.Context, token string) (username string, err error) { |
| 638 | trReq := &authv1.TokenReview{ |
| 639 | Spec: authv1.TokenReviewSpec{ |
| 640 | Token: token, |
| 641 | Audiences: []string{s.AgentAuthenticationOptions.AuthenticationAudience}, |
| 642 | }, |
| 643 | } |
| 644 | r, err := s.AgentAuthenticationOptions.KubernetesClient.AuthenticationV1().TokenReviews().Create(ctx, trReq, metav1.CreateOptions{}) |
| 645 | if err != nil { |
| 646 | return "", fmt.Errorf("Failed to authenticate request. err:%v", err) |
| 647 | } |
| 648 | |
| 649 | if r.Status.Error != "" { |
| 650 | return "", fmt.Errorf("lookup failed: %s", r.Status.Error) |
| 651 | } |
| 652 | |
| 653 | if !r.Status.Authenticated { |
| 654 | return "", fmt.Errorf("lookup failed: service account jwt not valid") |
| 655 | } |
| 656 | |
| 657 | // The username is of format: system:serviceaccount:(NAMESPACE):(SERVICEACCOUNT) |
| 658 | username = r.Status.User.Username |
| 659 | parts := strings.Split(username, ":") |
| 660 | if len(parts) != 4 { |
| 661 | return "", fmt.Errorf("lookup failed: unexpected username format") |
| 662 | } |
| 663 | // Validate the user that comes back from token review is a service account |
| 664 | if parts[0] != "system" || parts[1] != "serviceaccount" { |
| 665 | return "", fmt.Errorf("lookup failed: username returned is not a service account") |
| 666 | } |
| 667 | |
| 668 | ns := parts[2] |
| 669 | sa := parts[3] |
| 670 | if s.AgentAuthenticationOptions.AgentNamespace != ns { |
| 671 | return "", fmt.Errorf("lookup failed: incoming request from %q namespace. Expected %q", ns, s.AgentAuthenticationOptions.AgentNamespace) |
| 672 | } |
| 673 | |
| 674 | if s.AgentAuthenticationOptions.AgentServiceAccount != sa { |
| 675 | return "", fmt.Errorf("lookup failed: incoming request from %q service account. Expected %q", sa, s.AgentAuthenticationOptions.AgentServiceAccount) |
| 676 | } |
| 677 | |
| 678 | return username, nil |
| 679 | } |
| 680 | |
| 681 | func (s *ProxyServer) authenticateAgentViaToken(ctx context.Context) error { |
| 682 | md, ok := metadata.FromIncomingContext(ctx) |
| 683 | if !ok { |
| 684 | return fmt.Errorf("Failed to retrieve metadata from context") |
| 685 | } |
| 686 | |
| 687 | authContext := md.Get(header.AuthenticationTokenContextKey) |
| 688 | if len(authContext) == 0 { |
| 689 | return fmt.Errorf("Authentication context was not found in metadata") |
| 690 | } |
| 691 | |
| 692 | if len(authContext) > 1 { |
| 693 | return fmt.Errorf("too many (%d) tokens are received", len(authContext)) |
| 694 | } |
| 695 | |
| 696 | if !strings.HasPrefix(authContext[0], header.AuthenticationTokenContextSchemePrefix) { |
| 697 | return fmt.Errorf("received token does not have %q prefix", header.AuthenticationTokenContextSchemePrefix) |
| 698 | } |
| 699 | |
| 700 | username, err := s.validateAuthToken(ctx, strings.TrimPrefix(authContext[0], header.AuthenticationTokenContextSchemePrefix)) |
| 701 | if err != nil { |
| 702 | return fmt.Errorf("Failed to validate authentication token, err:%v", err) |
| 703 | } |
| 704 | |
| 705 | klog.V(5).InfoS("Agent successfully authenticated via token", "username", username) |
| 706 | return nil |
| 707 | } |
| 708 | |
| 709 | // Connect is for agent to connect to ProxyServer as next hop |
| 710 | func (s *ProxyServer) Connect(stream agent.AgentService_ConnectServer) error { |
| 711 | metrics.Metrics.ConnectionInc(metrics.Connect) |
| 712 | defer metrics.Metrics.ConnectionDec(metrics.Connect) |
| 713 | |
| 714 | backend, err := NewBackend(stream) |
| 715 | if err != nil { |
| 716 | klog.ErrorS(err, "Invalid backend") |
| 717 | return err |
| 718 | } |
| 719 | agentID := backend.GetAgentID() |
| 720 | |
| 721 | klog.V(5).InfoS("Connect request from agent", "agentID", agentID, "serverID", s.serverID) |
| 722 | labels := runpprof.Labels( |
| 723 | "serverCount", strconv.Itoa(s.serverCount), |
| 724 | "agentID", agentID, |
| 725 | ) |
| 726 | ctx := runpprof.WithLabels(context.Background(), labels) |
| 727 | runpprof.SetGoroutineLabels(ctx) |
| 728 | |
| 729 | if s.AgentAuthenticationOptions.Enabled { |
| 730 | if err := s.authenticateAgentViaToken(stream.Context()); err != nil { |
| 731 | klog.ErrorS(err, "Client authentication failed", "agentID", agentID) |
| 732 | return err |
| 733 | } |
| 734 | } |
| 735 | |
| 736 | h := metadata.Pairs(header.ServerID, s.serverID, header.ServerCount, strconv.Itoa(s.serverCount)) |
| 737 | if err := stream.SendHeader(h); err != nil { |
| 738 | klog.ErrorS(err, "Failed to send server count back to agent", "agentID", agentID) |
| 739 | return err |
| 740 | } |
| 741 | |
| 742 | klog.V(2).InfoS("Agent connected", "agentID", agentID, "serverID", s.serverID) |
| 743 | s.addBackend(backend) |
| 744 | defer s.removeBackend(backend) |
| 745 | |
| 746 | recvCh := make(chan *client.Packet, s.xfrChannelSize) |
| 747 | |
| 748 | go runpprof.Do(context.Background(), labels, func(context.Context) { s.serveRecvBackend(backend, agentID, recvCh) }) |
| 749 | |
| 750 | defer func() { |
| 751 | close(recvCh) |
| 752 | }() |
| 753 | |
| 754 | stopCh := make(chan error) |
| 755 | go runpprof.Do(context.Background(), labels, func(context.Context) { s.readBackendToChannel(backend, recvCh, stopCh) }) |
| 756 | |
| 757 | return <-stopCh |
| 758 | } |
| 759 | |
| 760 | func (s *ProxyServer) readBackendToChannel(backend *Backend, recvCh chan *client.Packet, stopCh chan error) { |
| 761 | agentID := backend.GetAgentID() |
| 762 | for { |
| 763 | in, err := backend.Recv() |
| 764 | if err == io.EOF { |
| 765 | klog.V(2).InfoS("Receive stream from agent is closed", "agentID", agentID) |
| 766 | close(stopCh) |
| 767 | return |
| 768 | } |
| 769 | if err != nil { |
| 770 | if status.Code(err) == codes.Canceled { |
| 771 | klog.V(2).InfoS("Stream read from agent cancelled", "agentID", agentID) |
| 772 | } else { |
| 773 | klog.ErrorS(err, "Receive stream from agent read failure", "agentID", agentID) |
| 774 | } |
| 775 | stopCh <- err |
| 776 | close(stopCh) |
| 777 | return |
| 778 | } |
| 779 | |
| 780 | select { |
| 781 | case recvCh <- in: // Send didn't block, carry on. |
| 782 | default: // Send blocked; record it and try again. |
| 783 | klog.V(2).InfoS("Receive channel from agent is full", "agentID", agentID) |
| 784 | fullRecvChannelMetric := metrics.Metrics.FullRecvChannel(metrics.Connect) |
| 785 | fullRecvChannelMetric.Inc() |
| 786 | recvCh <- in |
| 787 | fullRecvChannelMetric.Dec() |
| 788 | } |
| 789 | } |
| 790 | } |
| 791 | |
| 792 | // route the packet back to the correct client |
| 793 | func (s *ProxyServer) serveRecvBackend(backend *Backend, agentID string, recvCh <-chan *client.Packet) { |
| 794 | defer func() { |
| 795 | // Drain recvCh to ensure that readBackendToChannel is not blocked on a channel write. |
| 796 | // This should never happen, as termination of this function should only be initiated by closing recvCh. |
| 797 | discardedPktCount := 0 |
| 798 | for range recvCh { |
| 799 | discardedPktCount++ |
| 800 | } |
| 801 | if discardedPktCount > 0 { |
| 802 | klog.V(2).InfoS("Discard packets while exiting serveRecvBackend", "pktCount", discardedPktCount, "agentID", agentID) |
| 803 | } |
| 804 | }() |
| 805 | |
| 806 | defer func() { |
| 807 | // Close all established connections when the agent connection is closed |
| 808 | // TODO(#126): connections in PendingDial state should also be closed. |
| 809 | established, err := s.removeEstablishedForBackendConn(agentID, backend) |
| 810 | if err != nil { |
| 811 | return |
| 812 | } |
| 813 | if len(established) > 0 { |
| 814 | klog.V(2).InfoS("Close established connections to agent", |
| 815 | "count", len(established), "agentID", agentID) |
| 816 | } |
| 817 | |
| 818 | for _, frontend := range established { |
| 819 | pkt := &client.Packet{ |
| 820 | Type: client.PacketType_CLOSE_RSP, |
| 821 | Payload: &client.Packet_CloseResponse{ |
| 822 | CloseResponse: &client.CloseResponse{}, |
| 823 | }, |
| 824 | } |
| 825 | pkt.GetCloseResponse().ConnectID = frontend.connectID |
| 826 | if err := frontend.send(pkt); err != nil { |
| 827 | klog.ErrorS(err, "CLOSE_RSP to frontend failed", "agentID", agentID) |
| 828 | } |
| 829 | } |
| 830 | }() |
| 831 | |
| 832 | for pkt := range recvCh { |
| 833 | switch pkt.Type { |
| 834 | case client.PacketType_DIAL_RSP: |
| 835 | resp := pkt.GetDialResponse() |
| 836 | klog.V(5).InfoS("Received DIAL_RSP", "dialID", resp.Random, "agentID", agentID, "connectionID", resp.ConnectID) |
| 837 | |
| 838 | frontend := s.PendingDial.Remove(resp.Random) |
| 839 | if frontend == nil { |
| 840 | klog.V(2).InfoS("DIAL_RSP not recognized; dropped", "dialID", resp.Random, "agentID", agentID, "connectionID", resp.ConnectID) |
| 841 | metrics.Metrics.ObserveDialFailure(metrics.DialFailureUnrecognizedResponse) |
| 842 | if resp.ConnectID != 0 { |
| 843 | s.sendBackendClose(backend, resp.ConnectID, resp.Random, "unknown dial id") |
| 844 | } |
| 845 | } else { |
| 846 | dialErr := false |
| 847 | if resp.Error != "" { |
| 848 | // Dial response with error should not contain a valid ConnID. |
| 849 | klog.ErrorS(errors.New(resp.Error), "DIAL_RSP contains failure", "dialID", resp.Random, "agentID", agentID) |
| 850 | metrics.Metrics.ObserveDialFailure(metrics.DialFailureErrorResponse) |
| 851 | dialErr = true |
| 852 | } |
| 853 | err := frontend.send(pkt) |
| 854 | if err != nil { |
| 855 | klog.ErrorS(err, "DIAL_RSP send to frontend stream failure", |
| 856 | "dialID", resp.Random, "agentID", agentID, "connectionID", resp.ConnectID) |
| 857 | if !dialErr { // Avoid double-counting. |
| 858 | metrics.Metrics.ObserveDialFailure(metrics.DialFailureSendResponse) |
| 859 | } |
| 860 | // If we never finish setting up the tunnel for ConnectID, then the connection is dead. |
| 861 | // Currently, the agent will no resend DIAL_RSP, so connection is dead. |
| 862 | // We already attempted to tell the frontend that. We should ensure we tell the backend. |
| 863 | s.sendBackendClose(backend, resp.ConnectID, resp.Random, "dial error") |
| 864 | dialErr = true |
| 865 | } |
| 866 | // Avoid adding the frontend if there was an error dialing the destination |
| 867 | if dialErr { |
| 868 | break |
| 869 | } |
| 870 | frontend.connectID = resp.ConnectID |
| 871 | frontend.agentID = agentID |
| 872 | // TODO: this connection may be cleaned on serveRecvFrontend exit, make it independent. |
| 873 | s.addEstablished(agentID, resp.ConnectID, frontend) |
| 874 | close(frontend.connected) |
| 875 | metrics.Metrics.ObserveDialLatency(time.Since(frontend.start)) |
| 876 | klog.V(3).InfoS("Proxy connection established", |
| 877 | "dialID", resp.Random, |
| 878 | "connectionID", resp.ConnectID, |
| 879 | "agentID", agentID, |
| 880 | "dialAddress", frontend.dialAddress, |
| 881 | "dialDuration", time.Since(frontend.start), |
| 882 | ) |
| 883 | } |
| 884 | |
| 885 | case client.PacketType_DIAL_CLS: |
| 886 | resp := pkt.GetCloseDial() |
| 887 | klog.V(5).InfoS("Received DIAL_CLS", "agentID", agentID, "dialID", resp.Random) |
| 888 | frontend := s.PendingDial.Remove(resp.Random) |
| 889 | if frontend == nil { |
| 890 | klog.V(2).InfoS("DIAL_CLS not recognized; dropped", "dialID", resp.Random, "agentID", agentID) |
| 891 | } else { |
| 892 | if err := frontend.send(pkt); err != nil { |
| 893 | klog.ErrorS(err, "DIAL_CLS send to client stream error", "agentID", agentID, "dialID", resp.Random) |
| 894 | } else { |
| 895 | klog.V(5).InfoS("DIAL_CLS sent to frontend", "dialID", resp.Random) |
| 896 | } |
| 897 | klog.ErrorS(nil, "Dial terminated (DIAL_CLS) by backend", |
| 898 | "dialID", resp.Random, |
| 899 | "agentID", agentID, |
| 900 | "dialAddress", frontend.dialAddress, |
| 901 | "dialDuration", time.Since(frontend.start), |
| 902 | ) |
| 903 | metrics.Metrics.ObserveDialFailure(metrics.DialFailureBackendClose) |
| 904 | } |
| 905 | |
| 906 | case client.PacketType_DATA: |
| 907 | resp := pkt.GetData() |
| 908 | klog.V(5).InfoS("Received data from agent", "bytes", len(resp.Data), "agentID", agentID, "connectionID", resp.ConnectID) |
| 909 | if resp.ConnectID == 0 { |
| 910 | klog.ErrorS(nil, "Received packet missing ConnectID from agent", "packetType", "DATA") |
| 911 | continue |
| 912 | } |
| 913 | |
| 914 | frontend, err := s.getFrontend(agentID, resp.ConnectID) |
| 915 | if err != nil { |
| 916 | klog.V(2).InfoS("could not get frontend client; closing connection", "agentID", agentID, "connectionID", resp.ConnectID, "error", err) |
| 917 | s.sendBackendClose(backend, resp.ConnectID, 0, "missing frontend") |
| 918 | break |
| 919 | } |
| 920 | if err := frontend.send(pkt); err != nil { |
| 921 | klog.ErrorS(err, "send to client stream failure", "agentID", agentID, "connectionID", resp.ConnectID) |
| 922 | } else { |
| 923 | klog.V(5).InfoS("DATA sent to frontend") |
| 924 | } |
| 925 | |
| 926 | case client.PacketType_CLOSE_RSP: |
| 927 | resp := pkt.GetCloseResponse() |
| 928 | klog.V(5).InfoS("Received CLOSE_RSP", "agentID", agentID, "connectionID", resp.ConnectID) |
| 929 | frontend := s.removeEstablished(agentID, resp.ConnectID) |
| 930 | if frontend == nil { |
| 931 | // assuming it is already closed, just log it |
| 932 | klog.V(2).InfoS("could not get frontend client for closing", "agentID", agentID, "connectionID", resp.ConnectID) |
| 933 | break |
| 934 | } |
| 935 | if err := frontend.send(pkt); err != nil { |
| 936 | // Normal when frontend closes it. |
| 937 | klog.ErrorS(err, "CLOSE_RSP send to client stream error", "agentID", agentID, "connectionID", resp.ConnectID) |
| 938 | } else { |
| 939 | klog.V(5).InfoS("CLOSE_RSP sent to frontend", "connectionID", resp.ConnectID) |
| 940 | } |
| 941 | |
| 942 | case client.PacketType_DRAIN: |
| 943 | klog.V(2).InfoS("agent is draining", "agentID", agentID) |
| 944 | default: |
| 945 | klog.V(5).InfoS("Ignoring unrecognized packet from backend", "packet", pkt, "agentID", agentID) |
| 946 | } |
| 947 | } |
| 948 | klog.V(5).InfoS("Close backend of agent", "agentID", agentID) |
| 949 | } |
| 950 | |
| 951 | func (s *ProxyServer) sendBackendClose(backend *Backend, connectID int64, random int64, reason string) { |
| 952 | agentID := backend.GetAgentID() |
| 953 | pkt := &client.Packet{ |
| 954 | Type: client.PacketType_CLOSE_REQ, |
| 955 | Payload: &client.Packet_CloseRequest{ |
| 956 | CloseRequest: &client.CloseRequest{ |
| 957 | ConnectID: connectID, |
| 958 | }, |
| 959 | }, |
| 960 | } |
| 961 | if err := backend.Send(pkt); err != nil { |
| 962 | klog.V(5).ErrorS(err, "Failed to send close to agent", "closeReason", reason, "dialID", random, "agentID", agentID, "connectionID", connectID) |
| 963 | } |
| 964 | } |
| 965 | |
| 966 | func (s *ProxyServer) sendBackendDialClose(backend *Backend, random int64, reason string) { |
| 967 | agentID := backend.GetAgentID() |
| 968 | pkt := &client.Packet{ |
| 969 | Type: client.PacketType_DIAL_CLS, |
| 970 | Payload: &client.Packet_CloseDial{ |
| 971 | CloseDial: &client.CloseDial{ |
| 972 | Random: random, |
| 973 | }, |
| 974 | }, |
| 975 | } |
| 976 | if err := backend.Send(pkt); err != nil { |
| 977 | klog.V(5).ErrorS(err, "Failed to send dial close to agent", "closeReason", reason, "dialID", random, "agentID", agentID) |
| 978 | } |
| 979 | } |
| 980 | |
| 981 | func (s *ProxyServer) sendFrontendClose(frontend *GrpcFrontend, connectID int64, reason string) { |
| 982 | pkt := &client.Packet{ |
| 983 | Type: client.PacketType_CLOSE_RSP, |
| 984 | Payload: &client.Packet_CloseResponse{ |
| 985 | CloseResponse: &client.CloseResponse{ |
| 986 | ConnectID: connectID, |
| 987 | Error: reason, |
| 988 | }, |
| 989 | }, |
| 990 | } |
| 991 | if err := frontend.Send(pkt); err != nil { |
| 992 | klog.V(5).ErrorS(err, "Failed to send close to frontend", "closeReason", reason, "connectionID", connectID) |
| 993 | } |
| 994 | } |